Bloc: Add event inside onWillPop

Created on 30 Sep 2020  路  2Comments  路  Source: felangel/bloc

I tried to create app that on Home page have list of items, and when adding new item showing new page using state (to avoid using Navigator). Problem begins when user tries to go back from second screen using Android Back Button.
I tried overwrite onWillPop according to your suggestion in #352, but for some reason that doesn't work.

BlocProvider(
 create: (context) => TestblocBloc(),
 child: WillPopScope(
  onWillPop: () async {
   BlocProvider.of<TestblocBloc>(context).add(GoBackEvent());
   return Future.value(false);
   },
   child: Scaffold(
    body: BlocBuilder<TestblocBloc, TestblocState>(
     builder: (context, state) {
      if (state is TestblocInitial) return FirstPage();
      if (state is SecondPageState) return SecondPage();
      return null;
     },
    ),
   ),
  ),
 ),

Minimal example can be found here
In this example action on Second page flat button action BlocProvider.of<TestblocBloc>(context).add(GoBackEvent()) works flawless but when Android Back Button is clicked onWillPop function is called with no effect (It no longer exits app but it doesn't go back to the first page either).

So question is have I done something wrong or this approach is no longer valid?

question

Most helpful comment

Works perfect, thank you.

All 2 comments

Hi @Grekkq 馃憢

Fixed your issue in this PR.

Bloc retrieval wasn't working inside WillPopScope because of the context being the same as to the one where you provided the bloc. Wrapping with a Builder solves this. Alternatively you could just extract the subtree starting at WillPopScope in a separate widget.

Works perfect, thank you.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nerder picture nerder  路  3Comments

abinvp picture abinvp  路  3Comments

nhwilly picture nhwilly  路  3Comments

clicksocial picture clicksocial  路  3Comments

shawnchan2014 picture shawnchan2014  路  3Comments