Thamarakshan Pilla
Thamarakshan Pilla

Reputation: 45

How to await an asynchronous bloc event from a WillPopScope function in Flutter

Im building a Flutter app which contains multiple surveys based on different topics. There is a topic_screen where the topics will be listed and on clicking a topic, the respective survey_screen is displayed. I have made use of flutter_bloc package for the state management and used MVVM architecture.

In the survey_screen i have used WillPopScope() widget to trigger an autosave event. This autosave event triggers a block function contains calls to sqflite db saving function which is asynchronous.

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

I have added a Future.delayed function here to make sure the bloc function ends before running the function inside Future.delayed.

Instead of using Future.delayed, is there any other way to know when the particular event's bloc function gets over and then start the print and Navigator.pop

Upvotes: 2

Views: 3958

Answers (1)

KuKu
KuKu

Reputation: 7492

You just send 'SurveyAutoSaveEvent' at onWillPop of WillPopScope and
call 'Navigator.pop()' when received auto saving completed event using 'BlocListener'.
(If you are using BlocBuilder, use BlocConsumer instead of BlockBuilder and 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
    };

Upvotes: 3

Related Questions