如何在showModalBottomSheet中使用go_router实现模态内导航?
在showModalBottomSheet内用go_router实现内部导航
要让go_router的跳转页面限制在半屏模态框内,核心是给模态框嵌套独立的子Navigator,让导航逻辑在这个子Navigator内部执行,而非使用App的根Navigator。以下是具体实现步骤:
1. 创建模态框专用的NavigatorKey
先定义一个全局的NavigatorKey,用于控制模态框内部的导航状态:
final GlobalKey<NavigatorState> _modalNavigatorKey = GlobalKey<NavigatorState>();
2. 构建带嵌套Navigator的模态框
在showModalBottomSheet的builder中,返回固定高度的容器(实现半屏效果),内部嵌套Navigator组件,关联刚才创建的key,并配置初始路由和路由生成规则:
showModalBottomSheet( context: context, isScrollControlled: true, // 允许模态框调整高度 builder: (context) { // 设置模态框为屏幕高度的50% return SizedBox( height: MediaQuery.of(context).size.height * 0.5, child: Navigator( key: _modalNavigatorKey, initialRoute: '/modal/home', // 模态框初始页面路由 onGenerateRoute: (RouteSettings settings) { switch (settings.name) { case '/modal/home': return MaterialPageRoute( builder: (_) => const ModalHomePage(), ); case '/modal/detail': // 可传递参数 final args = settings.arguments as Map?; return MaterialPageRoute( builder: (_) => ModalDetailPage(data: args?['data']), ); default: return null; } }, ), ); }, );
3. 在模态框页面内执行内部跳转
在模态框的初始页面(比如ModalHomePage)中,点击按钮时使用模态框的NavigatorKey触发跳转,新页面就会显示在半屏模态框内:
ElevatedButton( onPressed: () { // 跳转到模态框内的详情页,可携带参数 _modalNavigatorKey.currentState?.pushNamed( '/modal/detail', arguments: {'data': '测试参数'}, ); }, child: const Text('打开详情页'), );
补充:结合GoRouter全局路由配置
如果你想复用GoRouter的全局路由定义,只需在GoRouter的routes中添加模态框专属路由,然后在子Navigator的onGenerateRoute中调用GoRouter的路由生成器即可:
// 全局GoRouter配置 final GoRouter _router = GoRouter( routes: [ GoRoute(path: '/', builder: (_, __) => const HomePage()), // 模态框专属路由 GoRoute( path: '/modal/home', builder: (_, __) => const ModalHomePage(), ), GoRoute( path: '/modal/detail', builder: (_, state) => ModalDetailPage(data: state.extra as String?), ), ], ); // 模态框内的Navigator配置 Navigator( key: _modalNavigatorKey, initialRoute: '/modal/home', onGenerateRoute: _router.routeInformationParser?.parseRouteInformation, );
这样既可以统一管理路由,又能保证模态框内的跳转被限制在半屏区域内。
内容的提问来源于stack exchange,提问作者ryandra
相关产品推荐
相关产品推荐

