In a Nested Navigator Structure of Flutter, How do you get the a Specific Navigator?

前端 未结 2 1970
孤城傲影
孤城傲影 2020-12-28 15:06

I have this problem when I have Nested Navigators. So something like,

class App extends StatelessWidget {
  @override
  Widget build(BuildContex         


        
2条回答
  •  星月不相逢
    2020-12-28 15:45

    Most of the time, you'll have only 2 Navigator.

    Which means to obtain the nested one, do:

    Navigator.of(context)
    

    And to obtain the root one do:

    Navigator.of(context, rootNavigator: true)
    

    For more complex architecture, the easiest by far is to use GlobalKey (since you'll never read Navigators during build)

    final GlobalKey key =GlobalKey();
    final GlobalKey key2 =GlobalKey();
    
    class Foo extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          navigatorKey: key,
          home: Navigator(
            key: key2,
          ),
        );
      }
    }
    

    Which you can then use this way:

    key.currentState.pushNamed('foo')
    

提交回复
热议问题