Gicminos
Gicminos

Reputation: 960

flutter - android back button does not call onWillPop of WillPopScope

I would like to exit my application. I have implemented a WillPopScope, but it looks like the onWillPop function is not being called at all. I tried many things like swap WillPopScope with Scaffold, changing the return value of the function, but it just looks like it is not working as expected.

My code:

Future<bool> _willPopCallback() async {
  exit(0);
  // await showDialog or Show add banners or whatever
  // then
  return true; // return true if the route to be popped
}


return Scaffold(
    appBar: MyAppBar(
      leading: DrawerAction(),
      title: Text(AppLocalizations.of(context).textCapitalized('home_page')),
      onSearch: (searchTerms) => this.search(searchTerms, context),
    ),
    body: new WillPopScope(
      onWillPop: _willPopCallback, // Empty Function.
      child: //my screen widgets

I am not sure if this is a bug I should report to flutter or I am doing something wrong. Happy to provide more code on request.

I have tried:

exit(0);
Navigator.of(context).pop();
SystemChannels.platform.invokeMethod('SystemNavigator.pop');

Thanks in advance!

Upvotes: 24

Views: 47121

Answers (9)

IvanPavliuk
IvanPavliuk

Reputation: 1810

I my case onWillPop didn't call because I had a custom AppBar and tried to call Navigator.pop(context) instead of Navigator.maybePop(context).

Upvotes: 4

Lucrezia C
Lucrezia C

Reputation: 23

This is a late answer but I hope can helps someone.

The @Gicminos answer was right. If you have nested scaffold willPopScope not worked. I wanna add some info in case you need.

I have a Scaffold containing bottomNavBar. Every Item in bottomNav is a Navigator which children are Scaffold (you notice that in this moment there are scaffolds innested).

This is my MainScaffold containing the bottom bar:

...

_navigatorKeys = {
      TabItem.tabOne: tabOneKey,
      TabItem.tabTwo: GlobalKey<NavigatorState>(),
    };
...
@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        //check if there are pages in stack so it can pop;
        var navigatorState =(_navigatorKeys.values.toList([_selectedIndex]as GlobalKey<NavigatorState>).currentState;
        if ( navigatorState !=null) {
          if (!await navigatorState
              .maybePop()) return true;
        }
        return false;
      },
      child: Scaffold(
        body: SafeArea(
          child: IndexedStack(
            index: _selectedIndex,
            children: _pages,
          ),
        ),
        resizeToAvoidBottomInset: true,
        bottomNavigationBar: Container(...)
        ...
}

If you wrap with a WillPopScope widget also your children like in the code below:

  @override
  Widget build(BuildContext context) {
    var t = AppLocalizations.of(context)!;

    return WillPopScope(
      onWillPop: () async {
        debugPrint("test");
        return true;
      },
      child: Scaffold(...)
}

both onWillPop will be called (in main scaffold and children scaffold). In the example the first one will pop only if can (there are page in navigator stack), the second one will be called immediatly after the first one and it will call the debugPrint function before returned

Upvotes: 1

Lee Probert
Lee Probert

Reputation: 10859

I have been battling this and initially thought it had something to do with the nested Scaffold widgets as the OP had mentioned in their answer above. I tested this though and still had the same problem. The answer for me was that my root Scaffold was a child of a Navigator. It worked as soon as I removed the Scaffold as a child of the Navigator. Thankfully I didn't need a Navigator at the root level anyway as I was using an IndexedStack which has multiple Navigator widgets in it.

Upvotes: 1

adrianvintu
adrianvintu

Reputation: 1425

Another possible reason: my implementation of _onWillPop() was throwing an exception and the code inside _onWillPop() was ignored. The exception did not appear in the log.

I resolved it by using a TRY/CATCH inside _onWillPop(), and handling all code paths.

Upvotes: 1

Rohit Sharma
Rohit Sharma

Reputation: 167

I also stuck in the same problem but after a lot of searching, I found that this error is related to my parent container.

return WillPopScope(
      onWillPop: () => _onWillPop(),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          ...
          ],
        ),

Upvotes: 1

user2077235
user2077235

Reputation: 51

Modify the code to return WillPopScope, and have Scaffold as a child.

return new WillPopScope(
    onWillPop: _willPopCallback,
    child: new Scaffold(
     //then the rest of your code...

Upvotes: 4

phoenix
phoenix

Reputation: 401

i know i am too late, but the problem still exists. maybe i found the right solution. make sure you are passing MaterialApp to the runApp method like this:

runApp(MaterialApp(home: MyFirstPage()));

this works for me for all my application's widgets. if you do not want to use it just wrap your widget in MaterialApp but do not forget that in every MaterialApp instance a new Navigator is created, so for me i just created one as above and in all my pages i just used scaffold and everything is ok.

Upvotes: 1

Gicminos
Gicminos

Reputation: 960

I managed to solve my problem and I think it is a very particular case, but it still might be helpful to someone.

TL;DR: Ensure that you dont have multiple Scaffolds in your widgets

I was using IndexedStack in my menu navigator, obviously wrapped with a Scaffold. The pages of the stack had Scaffold as well, and with this combination WillPopScope was not working neither in the navigator page neither in its stack pages. I solved by removing all the Scaffolds in the stack pages and having only one in the controller. In this way I managed to use WillPopScope correctly.

Upvotes: 25

HasilT
HasilT

Reputation: 2609

First of all do not ever use exit(0). It may be fine in Android environment, but apple won't allow the app on app store if it programmatically shuts down itself.

Here in the docs of onWillPop it clearly mentions that function should resolves to a boolean value.

Future<bool> _willPopCallback() async {
   // await showDialog or Show add banners or whatever
   // then
   return Future.value(true);
}

This only works if your current page is the root of navigation stack.

Upvotes: 19

Related Questions