【问题标题】:How to await an asynchronous bloc event from a WillPopScope function in Flutter如何在 Flutter 中等待来自 WillPopScope 函数的异步 bloc 事件
【发布时间】:2021-07-13 21:24:12
【问题描述】:

我正在构建一个 Flutter 应用,其中包含基于不同主题的多项调查。有一个 topic_screen,其中将列出主题,单击主题时,会显示相应的 survey_screen。我使用 flutter_bloc 包进行状态管理,并使用了 MVVM 架构

survey_screen 中,我使用了 WillPopScope() 小部件来触发自动保存事件。 此自动保存事件触发一个块函数,其中包含对异步的 sqflite 数据库保存函数的调用。

survey_screen :

@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
          BlocProvider.of<SurveyBloc>(context).add(SurveyAutoSaveEvent());

          await Future.delayed(const Duration(seconds: 5), () {
           print("After Autosave");
           Navigator.pop(context, BlocProvider.of<SurveyBloc>(context).viewModel);
          });

          return Future.value(false);
      },
      child: //remaining code

我在这里添加了一个 Future.delayed 函数,以确保 bloc 函数在 Future.delayed 中运行该函数之前结束。

除了使用 Future.delayed,还有其他方法可以知道特定事件的 bloc 函数何时结束,然后启动 printNavigator。弹出

【问题讨论】:

    标签: flutter mvvm flutter-bloc


    【解决方案1】:

    您只需在 WillPopScope 的 onWillPop 上发送“SurveyAutoSaveEvent”,
    使用“BlocListener”收到自动保存完成事件时调用“Navigator.pop()”。
    (如果您使用 BlocBuilder,请使用 BlocConsumer 而不是 BlockBuilder 和 BlocListener。)

    BlocListener<BlocA, BlocAState> (
          bloc: blocA,
          listener: (context, state) {
            if (state is SurveyAutoSaveCompleted) {
              print("After Autosave");
                Navigator.pop(context, BlocProvider.of<SurveyBloc>(context).viewModel);
                });
            }
          },
          child: WillPopScope(
            onWillPop: () async {
                BlocProvider.of<SurveyBloc>(context).add(SurveyAutoSaveEvent());
    
                await Future.delayed(const Duration(seconds: 5), () {
                
    
                return false;
            },
            child: //remaining code
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 2019-03-21
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多