在Flutter中的底部表中显示插座进度

nom7f22z  于 2023-08-07  发布在  Flutter
关注(0)|答案(2)|浏览(113)

我在Flutter中使用插座。我想用线性百分比指标在底部表格中显示进度。下面是我的initSocket方法:

initSocket(String livelapseId) {
socket = IO.io(Endpoints.baseUrl, <String, dynamic>{
  'autoConnect': true,
  'transports': ['websocket'],
});
// socket.connect();
socket!.onConnect((_) {
  print('Connection established');
  socket!.emit('joinRoom', "livelapse:$livelapseId");
  // socket!.on("livelapse:progress", (livelapseId, data, progress) => null);

  socket!.on('livelapse:progress', (data) {
    print("progress" + data.toString());
    print("operation" + data["operation"].toString());
    setState(() {
      _progressBar = double.parse(data["progress"].toString());

    });
    // progressTabCtx.updateItem(itemData._id, { text: operation, progress: progress });
  });

  socket!.on('livelapse:completed', (data) {
    print("completed" + data.toString());
    // progressTabCtx.updateItem(itemData._id, { text: operation, progress: progress });
  });
  socket!.on('livelapse:errored', (data) {
    print("errored" + data.toString());
    // progressTabCtx.updateItem(itemData._id, { text: operation, progress: progress });
  });
});
// socket!.destroy();
socket!.onDisconnect((_) => print('Connection Disconnection'));
socket!.onConnectError((err) => print(err));
socket!.onError((err) => print(err));

字符串
}
这是我调用initsocket和showbottomsheet的代码。我想在底部页面显示progressbar:第一个月
下面是我的底部表方法:
_showProgressBottomSheet(context,double progress){

return showModalBottomSheet(
  context: context,
  backgroundColor: Colors.transparent,
  builder: (context) => StatefulBuilder(
    
    builder: (BuildContext context, StateSetter setState) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 28.h),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(16.r), topRight: Radius.circular(16.r)),
          color: Colors.white,
        ),
        height: 288.h,
        width: MediaQuery.of(context).size.width,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  'Generating LiveLapse',
                  style: TextStyle(
                      color: Helper.baseBlack,
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w500),
                ),
              ],
            ),
            SizedBox(height: 20.h),
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ListTile(
                  contentPadding: EdgeInsets.zero,
                  isThreeLine: true,
                  leading: Container(
                    padding:
                        EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.h),
                    width: 32.w,
                    height: 32.h,
                    decoration: BoxDecoration(
                        color: Color.fromRGBO(229, 240, 255, 1),
                        borderRadius: BorderRadius.circular(32.r),
                        border: Border.all(
                            color: Color.fromRGBO(245, 249, 255, 1),
                            width: 4.w)),
                    child: SvgPicture.asset(
                      'assets/images/film.svg',
                    ),
                  ),
                  title: Text(
                    "Camera 2 - The Bridges.mp4",
                    style: TextStyle(
                        color: Helper.textColor700,
                        fontSize: 14,
                        fontWeight: FontWeight.w500),
                  ),
                  subtitle: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          "Fetching images",
                          style: TextStyle(
                              color: Helper.textColor600,
                              fontSize: 14,
                              fontWeight: FontWeight.w400),
                        ),
                        SizedBox(height: 10.h),
                        Row(mainAxisSize: MainAxisSize.max,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                         children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(4.r),
                            child: LinearPercentIndicator(
                              width: 210.w,
                              fillColor: Helper.textColor300,
                              backgroundColor: Helper.textColor300,
                              progressColor: Helper.primary,
                              padding: EdgeInsets.zero,
                              curve: Curves.easeInOut,
                              barRadius: Radius.circular(4.r),
                              lineHeight: 8.h,
                              percent: _progressBar / 100
                            ),
                          ),
                          Text(
                            "${(_progressBar).toInt()}%",
                            style: TextStyle(
                                color: Helper.textColor700,
                                fontSize: 14,
                                fontWeight: FontWeight.w500),
                          )
                        ])
                      ]),
                  trailing: SvgPicture.asset(
                    'assets/images/checkbox_base.svg',
                  ),
                ),
                SizedBox(height: 20.h),
                Container(
                  height: 52.h,
                  width: double.infinity,
                  child: ElevatedButton(
                    child: Text(
                      "Close",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w500),
                      // currentIndex == contents.length - 1 ? "Continue" : "Next"
                    ),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStatePropertyAll(Helper.baseBlack),
                        shape: MaterialStateProperty.all(
                          RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.r),
                          ),
                        )),
                    onPressed: () {
                      context.pop();
                    },
                  ),
                ),
              ],
            ),
          ],
        ),
      );
    }
  ),
);


}
进度条是不移动,如果我使用它以外的底部表方法(例如,在屏幕的任何地方,它是工作正常。套接字连接,一切正常)。底部工作表不更新进度条。我还使用了Stateful Builder

ggazkfy8

ggazkfy81#

我不完全理解你的问题,但我知道一种方法来监听不同类中的套接字。可能对你有帮助。

*第一个:

在主或某处定义变量(不在任何类)并初始化变量

late Socket socket; //define socket variable

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
    _initSocket(yourStringVariable); //initialize your variable
  }
  ...
}

字符串

*然后:

我没有在函数中定义一个小部件树;相反,我更喜欢在另一个地方创建一个小部件并调用它,使它像一个新页面一样工作。

import 'package:YOUR_PROJECT/YOUR_SOCKET_VARIABLE_FILE.dart'; //import the file where the socket variable is defined

class YourBottomSheetClass extends StatefulWidget {
  const YourBottomSheetClass({super.key});

  @override
  State<YourBottomSheetClass> createState() => _YourBottomSheetClassState();
}

class _YourBottomSheetClassState extends State<YourBottomSheetClass> {

  @override
  void initState() {
    super.initState();
    socket.on('yourChannel',_yourFunc);
  }

  @override
  void dispose() {
    socket.off('yourChannel');
    super.dispose();
  }

  void _yourFunc(){
    ...
  }

  ...
}

***然后 *

更改底部工作表功能

_showProgressBottomSheet(context, _progressBar){  // this is your bottomsheet function
   return showModalBottomSheet(context: context, builder: (context) {
      return YourBottomSheetClass();
    },);
}

    • 终于**

在任何地方页面的构建方法中调用您的函数

Widget build(BuildContext context) {
  return Container(
    ...
    ...
    child: ElevatedButton(onPressed: (){
      _showProgressBottomSheet(context,progress);
    });
  );
}


希望对你有帮助。

yjghlzjz

yjghlzjz2#

在有状态小部件中,定义一个StateSetter变量,用于存储工作表状态。

class _YourWidgetState extends State<YourWidgetClass> {

  StateSetter? bottomSheetState; //add this line

  @override
  void initState() {
  ...

字符串
bottomSheetState变量赋值给StatefulBuilder给定的状态。

return showModalBottomSheet(
  context: context,
  backgroundColor: Colors.transparent,
  builder: (context) => StatefulBuilder(
    builder: (BuildContext context, StateSetter modalState) {

    bottomSheetState = modalState; //add this line

    ...


更新进度时,调用bottomSheetState而不是setState

socket!.on('livelapse:progress', (data) {
  print("progress" + data.toString());
  print("operation" + data["operation"].toString());

  if(bottomSheetState != null){
    bottomSheetState(() {
      _progressBar = double.parse(data["progress"].toString());
    });
  }

  // progressTabCtx.updateItem(itemData._id, { text: operation, progress: progress });
});

相关问题