Flutter嵌套路由问题

时间:2020-08-02 19:22:28

标签: flutter routes nested navigation

我正在尝试在Flutter中实现嵌套路由。

这是我的项目树中的示例。

enter image description here

当我在Page小部件上并尝试使用后退按钮回到LandingPage小部件时,该应用程序将关闭。

有人可以帮我吗

这是一个代码示例:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Code Sample for Navigator',
      // MaterialApp contains our top-level Navigator
      initialRoute: '/',
      routes: {
        '/': (BuildContext context) => Home(),
        '/app': (BuildContext context) => App(),
      },
    );
  }
}



class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      ..
      child: Builder(
        builder: (context)=> Navigator(
          initialRoute: 'LandingPage',

          onGenerateRoute: (RouteSettings settings) {
            WidgetBuilder builder;
            switch (settings.name) {
              case 'LandingPage':
                builder = (BuildContext _) => LandingPage();
                break;
              case 'Page':
                builder = (BuildContext _) => Page();
                break;
              default:
                throw Exception('Invalid route: ${settings.name}');
            }
            return MaterialPageRoute(builder: builder, settings: settings);
          },

        ); 
      )
    );
  }
}


2 个答案:

答案 0 :(得分:0)

以标准方式路由到此类页面

    initialRoute: "/screen1",
    routes: <String, WidgetBuilder>{
      '/screen1': (BuildContext context) =>  Screen1(),
      '/screen2': (BuildContext context) =>  Screen2(),
      '/screen3': (BuildContext context) =>  Screen3(),
      '/screen4': (BuildContext context) =>  Screen4()
    },
    onUnknownRoute: (RouteSettings settings) {
      return MaterialPageRoute<void>(
        settings: settings,
        builder: (BuildContext context) =>
            Scaffold(body: Center(child: Text('Not Found'))),
      );
    },
  )
);

答案 1 :(得分:0)

我通过正确使用Navigator.maybePop()WillPopScope()来使其正常工作。

根据Flutter的maybePop(),它代替pop()用于处理用户在设备后退按钮上的点击。

通过反转嵌套导航器中的行为,按下后退按钮不会弹出根导航器,而只会弹出嵌套导航器。

例如:

class SecondNavigator extends StatefulWidget {
  SecondNavigator({Key key}) : super(key: key);
  @override
  _SecondNavigatorState createState() => _SecondNavigatorState();
}

class _SecondNavigatorState extends State<SecondNavigator> {
  final GlobalKey<NavigatorState> navigatorKey = new GlobalKey();
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Navigator(
                key: navigatorKey,
                ...
              ),
      onWillPop: () async {
        final NavigatorState navigator = navigatorKey.currentState;
        return !await navigator.maybePop();        
      },
    );
  }
}

提供了完整的示例here

请务必查看willpop()的flutter文档,以更好地了解maypop()