我一直在寻找Flutter的一个很好的导航/路由器示例,但是我没有找到一个例子。
我想要实现的非常简单:
BottomNavigationBar的官方Flutter演示达到1,但后退按钮和路由无效。PageView和TabView的相同问题。还有许多其他教程通过实现MaterialApp路线来实现2和3,但是它们似乎都没有持久的导航栏。
是否有满足所有这些要求的导航系统示例?
您可以使用自定义的Navigator来满足这3个要求。
Flutter团队对此做了一个视频,下面是他们的文章:https : //medium.com/flutter/getting-to-the-bottom-of-navigation-in- flutter-b3e440b9386
基本上,您需要将脚手架的主体包装到一个自定义中Navigator:
Navigator
class _MainScreenState extends State<MainScreen> { final _navigatorKey = GlobalKey<NavigatorState>(); // ... @override Widget build(BuildContext context) { return Scaffold( body: Navigator( key: _navigatorKey, initialRoute: '/', onGenerateRoute: (RouteSettings settings) { WidgetBuilder builder; // Manage your route names here switch (settings.name) { case '/': builder = (BuildContext context) => HomePage(); break; case '/page1': builder = (BuildContext context) => Page1(); break; case '/page2': builder = (BuildContext context) => Page2(); break; default: throw Exception('Invalid route: ${settings.name}'); } // You can also return a PageRouteBuilder and // define custom transitions between pages return MaterialPageRoute( builder: builder, settings: settings, ); }, ), bottomNavigationBar: _yourBottomNavigationBar, ); } }
在底部导航栏中,只需使用以下命令即可导航到新custom中的新屏幕Navigator:
_navigatorKey.currentState.pushNamed('/yourRouteName');
为了实现第三个要求,这是Navigator.pop带你到一个视图,你将需要包装定制Navigator了WillPopScope:
Navigator.pop
WillPopScope
@override Widget build(BuildContext context) { return Scaffold( body: WillPopScope( onWillPop: () async { if (_navigatorKey.currentState.canPop()) { _navigatorKey.currentState.pop(); return false; } return true; }, child: Navigator( // ... ), ), bottomNavigationBar: _yourBottomNavigationBar, ); }
就是这样!无需手动处理弹出或管理自定义历史记录列表。