Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter - android back button does not call onWillPop of WillPopScope

Tags:

flutter

dart

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!

like image 735
Gicminos Avatar asked Feb 18 '20 17:02

Gicminos


People also ask

How do you use onWillPop in Flutter?

onWillPop: onWillPop is a callback method that returns a Future value; if true, the screen can be popped; if false, the screen will not be popped out. However, the screen can still be popped by calling the Navigator. pop(context).

How do I get rid of the back arrow on my AppBar Flutter?

The right and simplest way to remove back button on Appbar in Flutter is to set the automaticallyImplyLeading property of the AppBar to false and replace the old screen in a stack with the current/new screen.


Video Answer


1 Answers

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.

like image 138
Gicminos Avatar answered Sep 18 '22 07:09

Gicminos