Flutter Bottom Navigation Bar与Go Route跳转异常求助
解决GoRouter StatefulShellRoute中子页面无法返回父页面的问题
问题描述
开发二维码扫描应用时,使用GoRouter的StatefulShellRoute实现了包含Scan和Help的底部导航栏。页面流程为:启动页→扫描页(Scan Page)→结果页(Plastic Page)。但进入Plastic页面后,点击底部导航栏的Scan选项,无法返回Scan页面,始终停留在Plastic页面。
原因分析
StatefulShellRoute的goBranch方法默认切换分支时,会保留当前分支的导航栈状态。当处于Scan分支的子页面(/scan/plastic)时,再次点击Scan分支,默认只会切换到该分支,但不会重置导航栈到根页面(/scan)。
解决方案
修改底部导航栏的onDestinationSelected回调逻辑,当点击当前已选中的分支时,强制重置该分支的导航栈到初始路径。
修改LayoutScaffold代码
import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:recycle/main_p_dest.dart'; class LayoutScaffold extends StatelessWidget { const LayoutScaffold({required this.navigationShell, super.key}); final StatefulNavigationShell navigationShell; @override Widget build(BuildContext context) => Scaffold( body: navigationShell, bottomNavigationBar: NavigationBar( selectedIndex: navigationShell.currentIndex, onDestinationSelected: (index) { if (index == navigationShell.currentIndex) { // 点击当前选中的分支,重置到分支初始页面 navigationShell.goBranch( index, initialLocation: true, ); } else { navigationShell.goBranch(index); } }, indicatorColor: Theme.of(context).primaryColor, destinations: destinations .map( (destination) => NavigationDestination( icon: Icon(destination.icon), label: destination.label, selectedIcon: Icon(destination.icon, color: Colors.white), ), ) .toList(), ), ); }
关键说明
goBranch方法的initialLocation参数设置为true时,会跳转到当前分支的初始路径(即Scan分支的/scan),而非停留在子页面。- 确保从ScanPage跳转到Plastic页面时使用
context.push(Routes.plastic),保留导航栈的历史记录,这样重置操作才能生效。
验证效果
修改后,在Plastic页面点击底部导航栏的Scan选项,即可回到ScanPage;切换到Help页面再切回Scan,也会默认回到ScanPage。
内容的提问来源于stack exchange,提问作者Jayson
相关产品推荐
相关产品推荐

