如何从showModalBottomSheet退出并跳转到指定页面?
Flutter Bottom Sheet关闭后跳转页面问题解决
点击Bottom Sheet中的容器时,期望先关闭Bottom Sheet再跳转到EventScreen页面,但实际操作后,新页面是在Bottom Sheet内部的路由栈中打开的,而非根页面之上。相关代码如下:
完整布局代码
Row( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () { Navigator.pop(context); Navigator.push( context, MaterialPageRoute( builder: (context) => const EventScreen()), ); }, child: Container( height: 100, width: boxWidth, decoration: BoxDecoration( color: Colors.white, border: Border.all( color: const Color.fromARGB(255, 122, 121, 121), ), borderRadius: const BorderRadius.all( Radius.circular(10), ), ), padding: const EdgeInsets.all(5.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.trending_up_rounded, size: 40, color: Colors.blue, ), Text( 'Event Report', style: TextStyle(fontSize: fontSize), ), ]), ), ), ], )
关键逻辑代码
InkWell( onTap: () { Navigator.pop(context); Navigator.push( context, MaterialPageRoute( builder: (context) => const EventScreen()), ); }, )
解决方案
方案1:使用根导航器跳转
问题核心是Navigator.push使用的是Bottom Sheet的context,导致新页面被加入Bottom Sheet的子路由栈。改用根导航器的context即可解决:
InkWell( onTap: () { Navigator.pop(context); // 关闭Bottom Sheet // 获取根导航器执行跳转 Navigator.of(context, rootNavigator: true).push( MaterialPageRoute(builder: (context) => const EventScreen()), ); }, // ... 容器代码 )
方案2:利用Bottom Sheet的返回Future处理跳转
如果Bottom Sheet是通过showModalBottomSheet打开的,可以监听它的返回值,在Bottom Sheet关闭后再执行跳转:
- 打开Bottom Sheet时添加回调:
showModalBottomSheet( context: context, builder: (context) => YourBottomSheetWidget(), ).then((result) { // 根据返回值判断是否跳转 if (result == 'navigate_to_event') { Navigator.push( context, MaterialPageRoute(builder: (context) => const EventScreen()), ); } });
- 修改Bottom Sheet内的点击逻辑:
InkWell( onTap: () { // 关闭时传递跳转标记 Navigator.pop(context, 'navigate_to_event'); }, // ... 容器代码 )
内容的提问来源于stack exchange,提问作者mana
相关产品推荐
相关产品推荐

