Flutter: Pushing back button should allow the app

2019-07-25 08:33发布

问题:

I am using Flutter BottomSheet to display info, and would like to keep BottomSheet always visible even when back button is clicked, and to make it work I have explicitly handled onWillPop and to keep the BottomSheet in view even when user clicks back button, changing the route etc

The BottomSheet has a height of 200, and I want to keep it and yet allow the app to go background state when back button is clicked.

Widget _buildBody(context) => WillPopScope(
      onWillPop: () async {
        if(navigatorKey.currentState.canPop()) {
          navigatorKey.currentState.pop();
          return false;
        }else {
          // Returning true will remove the BottomSheet when back button is pressed, and if you press the back button one more time, the app will go to background state
          // return true;
        }
      },
      child: MaterialApp(
          navigatorKey: navigatorKey,
          onGenerateRoute: (route) => pagesRouteFactories[route.name]()));

Any ideas?

回答1:

Since you are using only one Navigator, Scaffold will push the "BottomSheet" route to the same Navigator as other routes. So it would not be possible to pop something in between.

I would suggest wrap Scaffold with another Navigator (just for pushing/poping bottom sheet). You will now have nested Navigators - one at MaterialApp level and one at Scaffold level. pop stuff from the "app" level Navigator - that wouldn't touch your bottom sheet. once there is nothing in "app" level Navigator the activity will close.

This should work in my opinion.

More info on Nested Navigator

Edit: code

@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{
        if(Navigator.of(context).canPop()) {
          Navigator.of(context).pop();
          return false;
        }
        return true;
      },
      child: Navigator(
        onGenerateRoute: (route) => MaterialPageRoute(
              builder: (context) => Scaffold(...),
            ),
      ),
    );
  }