Skip to content Skip to sidebar Skip to footer

Flutter Willpopscope For Nested Navigation

I have Flutter App with nested Navigator and I want to override 'onBackPressed' using WillPopScope in my nested screen. Let's say I have MainScreen, PrimaryScreen, and SecondaryScr

Solution 1:

When pressing the back button, I think it will use the main navigator of your app, because it doesn't know the nested navigator what you want to interact with.

To solve it, you have to assign a key for your navigator to be able to use it later. And adding a WillPopScope at widget which you use your nested navigator to handle user action.

Based on your example, I added some code. Noting, the maybePop() function will call the WillPopScope of your widget of the nested navigator. If you call pop(), it will pop directly, ignoring the WillPopScope of your widget.

classPrimaryScreenextendsStatelessWidget{
  final _navigatorKey = GlobalKey<NavigatorState>();

  @overrideWidgetbuild(BuildContext context) {
    returnWillPopScope(
        onWillPop: () async {
          if (_navigatorKey.currentState != null) {
            _navigatorKey.currentState!.maybePop();
            returnfalse;
          }

          returntrue;
        },
        child: Navigator(
          key: _navigatorKey,
          initialRoute: 'primary/pageone',
          onGenerateRoute: (RouteSettings settings) {
            WidgetBuilder builder;
            switch(settings.name){
              case'primary/pageone' :
                builder = (BuildContext _) =>PrimaryOneScreen();
                break;
              case'primary/pagetwo' :
                builder = (BuildContext _) =>PrimaryTwoScreen();
                break;
              case'primary/pagethree' :
                builder = (BuildContext _) =>PrimaryThreeScreen();
                break;
              default :
                throwException('Invalid route: ${settings.name}');
            }

            returnMaterialPageRoute(
              builder: builder,
              settings: settings
          );
        },
      ),
    );
  }

}

Solution 2:

Try with this link https://medium.com/flutter-community/flutter-push-pop-push-1bb718b13c31

Check Use-case : pushReplacementNamed tag description

Post a Comment for "Flutter Willpopscope For Nested Navigation"