23

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!

9 Answers 9

22

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.

4
  • Is there any option to get callback before widget ends and we also use multiple Scaffolds Jan 14, 2021 at 13:34
  • You need to remove the multiple Scaffolds if they are nested, then your willPopCallback is already before the widget ends, you are the one deciding to make it end or not by returning a boolean
    – Gicminos
    Jan 15, 2021 at 9:33
  • 1
    I have multiple Scaffolds because I need to set different app bars and navigations within certain sub-sections ... there has to be another way to resolve this. Dec 10, 2021 at 17:17
  • I am glad you found a solution, I am still not 100% sure what is the underlying logic about which widgets can and cannot be nested to use WillPopScope. Interesting fact is that we were both adopting similar solutions due to the usage of an IndexedStack.
    – Gicminos
    Dec 15, 2021 at 8:52
17

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.

6
  • I have updated my answer, exit(0) was my last desperate tentative to see it work, but I have tried everything I could find online. Now I will try to change false with Future.value(false); but it looks like the function does not get called at all when I press back
    – Gicminos
    Feb 18, 2020 at 18:19
  • @Gicminos have you tried wraping your scaffold with WillPopScope widget
    – HasilT
    Feb 18, 2020 at 18:29
  • Yes I did! Will try again with also Future.value(false);
    – Gicminos
    Feb 18, 2020 at 18:40
  • I'm almost certain that in order to allow your page to "pop" you need to return Future.value(true), not false. Feb 18, 2020 at 18:54
  • 2
    I will try again with Future.value(true) but I repeat, the function _willPopCallback() does not get called by WillPopScope!
    – Gicminos
    Feb 24, 2020 at 10:49
4

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...
1

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.

0
1

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,
          ...
          ],
        ),
1
  • 2
    What's the error you're referring to? Colors.transparent? Mar 9, 2022 at 13:14
1

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.

0
1

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.

1

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

1

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.