官方出品路由管理库go_router
路由管理需要的基本功能:
命名路由,方便通过系统消息栏等地方打开具体的路由页面,且能带上参数
路由嵌套,一个路由页面嵌套多个页面的场景非常多
可以自己封装Navigator,也可以使用第三方库,getx、go_router等都是不错的选择。go_router是官方出品。
Navigation 1 2 3 4 5 6 7 8 9 10 11 12 context.go(Uri (path: '/users/123' , queryParameters: {'filter' : 'abc' }).toString()); context.go('/123' , extra: 'abc' ); final String extraString = GoRouterState.of(context).extra! as String ;
转场动画 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 GoRoute( path: 'details' , pageBuilder: (context, state) { return CustomTransitionPage( key: state.pageKey, child: DetailsScreen(), transitionsBuilder: (context, animation, secondaryAnimation, child) { return FadeTransition( opacity: CurveTween(curve: Curves.easeInOutCirc).animate(animation), child: child, ); }, ); }, ),
命名路由 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 GoRoute( name: 'song' , path: 'songs/:songId' , builder: , ), TextButton( onPressed: () { context.goNamed('song' , pathParameters: {'songId' : 123 }); }, child: const Text('Go to song 2' ), ), TextButton( onPressed: () { final String location = context.namedLocation('song' , pathParameters: {'songId' : 123 }, queryParameters: {'filter' : 'abc' }); context.go(location); }, child: const Text('Go to song 2' ), ),
监听路由跳转 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 GoRouter router = GoRouter( initialLocation: '/splash' , routes: <RouteBase>[deskAppRoute], observers: [wsNavObserver], onException: (BuildContext ctx, GoRouterState state, GoRouter router) { router.go('/404' , extra: state.uri.toString()); }, ); MyNavObserver wsNavObserver = MyNavObserver(); class MyNavObserver extends RouteObserver {} class MyPageState extend State with RouteAware { void didChangeDependencies() { wsNavObserver.subscribe(this , ModalRoute.of(context)!); super .didChangeDependencies(); } }