如何等待来自 Flutter 中 WillPopScope 函数的异步 bloc 事件

时间:2021-07-13 21:24:12

标签: flutter mvvm flutter-bloc

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

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

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。弹出

1 个答案:

答案 0 :(得分:0)

您只需在 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
    };