Bloc: Question - Dispatch event when back button is pressed or swipe?

Created on 17 Jun 2019  路  4Comments  路  Source: felangel/bloc

Hello,

This is my question.
I want to dispatch an event when users press back button or swipe for iOS to fetch some data again to change the state of the previous screen

  @override
  void dispose() {
     _blocFromAnotherView.dispatch(Fetch());
    super.dispose();
  }

I tried to dispatch the event on dispose but that does not seem a good approach to me.

I want to do this because when users go back to the previous screen the state of that screen remains the same. So I want dispatch an event to change the state if user goes to the previous screen, but don't find a proper way to do it.

question

Most helpful comment

I'm still using version v0.11 gonna try to upgrade maybe I don't have any unexpected issues when update to new version.

Thanks gonna try that!

All 4 comments

Hi @frankrod 馃憢
Thanks for opening an issue!

Regarding your question, you can just use WillPopScope and then dispatch an event in onWillPop.

class CounterPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        BlocProvider.of<CounterBloc>(context).dispatch(CounterEvent.increment);
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text('Counter'),
        ),
        body: BlocBuilder(
          bloc: BlocProvider.of<CounterBloc>(context),
          builder: (BuildContext context, int count) {
            return Center(
              child: Text('$count'),
            );
          },
        ),
      ),
    );
  }
}

Hope that help! 馃憤

Thanks Felangel!
It is working but I'm having the same error message that I have with the dispose when I pop the views using popUntil:

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Bad state: Cannot add new events after calling close

0 _BroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:249:24)

How can avoid this error? can cause this an error in the app even though I'm just popping the views with popUntil?

@frankrod no problem!

The error means that you're calling dispose on your bloc and then later trying to dispatch an event to it. Make sure that you are only disposing the bloc when it is no longer needed. I recommend disposing the bloc in the widget where it is created or if you're using flutter_bloc v0.17.0 then BlocProvider disposes automatically for you.

Hope that helps 馃憤

I'm still using version v0.11 gonna try to upgrade maybe I don't have any unexpected issues when update to new version.

Thanks gonna try that!

Was this page helpful?
0 / 5 - 0 ratings