GoRouter在嵌套Tab路由中的状态恢复
解读
在国内 Flutter 工程面试中,这道题常被用来区分“只会写页面”与“真正做过复杂导航”的候选人。
面试官真正想听的是:
- 你能否把“底部 Tab + 内部子路由”这套国内 App 最常见结构用 GoRouter 表达出来;
- 当用户切 Tab 再回来,页面滚动位置、TextField 输入、Provider/Bloc 状态能否“原地复活”;
- 如果 App 被系统杀死后重建,上述状态是否还能恢复;
- 你是否知道 GoRouter 与 Navigator 2.0 的 RestorationBucket 如何协同,而不是简单套一个
AutomaticKeepAliveClientMixin就完事。
答不到“恢复原理 + 代码落地 + 边界 case”三层,基本会被判为“仅用过 demo 级别”。
知识点
- GoRouter 的 ShellRoute 与 StatefulShellRoute(1.2+)差异:前者共用同一个 Navigator,后者给每个 Tab 独立 Navigator,天然支持“Tab 级状态隔离”。
- RestorationMixin、RestorationBucket、RestorationScope:Flutter 框架级“状态复活”协议,与 Widget 生命周期解耦。
- RestorationId 的命名空间规则:必须在 Route 级别提前注册,不能在 build 阶段动态生成,否则重启后找不到桶。
- GoRouter 的
restorationScopeId与routerConfig.restorationPolicy:用来告诉框架“我的 RouteInformationParser 支持恢复”。 - Page 的
canRestore与maintainState:决定路由表是否把此页放进桶;ShellRoute 里每个 branch 的 Page 都要单独标记。 - 国内厂商 ROM 的“后台冻结”策略:App 退到后台 5~30 min 可能被杀,面试时要主动提到“必须测小米/华为杀进程场景”。
- 状态恢复的三种粒度:
a. ScrollController、TextEditingController 等“小部件级”——用 RestorableInt、RestorableTextEditingController;
b. BLoC/Cubit/Provider 的“业务级”——在 RestorableRouteMixin 里手动读写桶;
c. 网络列表的“缓存级”——配合 hive/shared_prefs 做序列化,恢复时同步加载,避免骨架屏闪烁。 - 常见坑:
- 把
StatefulWidget的restorationId写成随机 UUID,导致重启后找不到桶; - ShellRoute 的 builder 里又包了一层
MaterialPage,结果实际 Page 没有 restorationId; - 使用
IndexedStack保持 Tab 状态,却忘了在didUpdateWidget里把新路由信息同步给 RouteInformationProvider,导致系统返回键异常。
- 把
答案
下面给出一套可直接落地的“国内主流结构”示例:底部四个 Tab,每个 Tab 内部再推二级页面,要求切 Tab 不丢状态,杀进程重启也能恢复。
- 路由表定义(支持 restoration)
final _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root');
final _shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell');
final router = GoRouter(
restorationScopeId: 'appRouter', // 关键:整棵路由树共享一个桶
initialLocation: '/home',
navigatorKey: _rootNavigatorKey,
routes: [
StatefulShellRoute.indexedStack(
restorationScopeId: 'shell', // 给 Shell 本身也注册桶
branches: [
StatefulShellBranch(
restorationScopeId: 'homeBranch',
routes: [
GoRoute(
path: '/home',
restorationScopeId: 'homePage',
builder: (_, __) => const HomePage(),
routes: [
GoRoute(
path: 'detail',
restorationScopeId: 'homeDetail',
builder: (_, __) => const HomeDetailPage(),
),
],
),
],
),
// …其余三个 Branch 同理,都要给 restorationScopeId
],
builder: (context, state, navigationShell) {
return MainScaffold(navigationShell: navigationShell);
},
),
],
);
- 主框架
MainScaffold(底部 Tab)
class MainScaffold extends StatelessWidget {
final StatefulNavigationShell navigationShell;
const MainScaffold({required this.navigationShell, super.key});
void _tap(int index) {
navigationShell.goBranch(index,
initialLocation: index == navigationShell.currentIndex);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: navigationShell,
bottomNavigationBar: BottomNavigationBar(
currentIndex: navigationShell.currentIndex,
onTap: _tap,
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
// …
],
),
);
}
}
- 页面级状态恢复(以首页带滚动列表为例)
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with RestorationMixin, AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true; // 保证切换 Tab 不 dispose
final RestorableInt _selectedIndex = RestorableInt(0);
final RestorableDouble _scrollOffset = RestorableDouble(0);
late ScrollController _controller;
@override
String? get restorationId => 'homePageState'; // 与 Route 的桶对齐
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_selectedIndex, 'selectedIndex');
registerForRestoration(_scrollOffset, 'scrollOffset');
}
@override
void initState() {
super.initState();
_controller = ScrollController(
initialScrollOffset: _scrollOffset.value)
..addListener(() {
_scrollOffset.value = _controller.position.pixels;
});
}
@override
void dispose() {
_controller.dispose();
_selectedIndex.dispose();
_scrollOffset.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context); // 因为 mixin 了 AutomaticKeepAliveClientMixin
return ListView.builder(
controller: _controller,
itemCount: 100,
itemBuilder: (_, i) => ListTile(
title: Text('Item $i'),
selected: i == _selectedIndex.value,
onTap: () => setState(() => _selectedIndex.value = i),
),
);
}
}
- 应用入口打开 restoration
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return RootRestorationScope(
restorationId: 'root',
child: MaterialApp.router(
routerConfig: router,
restorationScopeId: 'materialApp',
debugShowCheckedModeBanner: false,
),
);
}
}
- 验证步骤(面试时主动说出来,体现测试意识)
a. 打开首页,列表滚到 200,选中第 8 项;
b. 切到第 2 个 Tab,再切回首页,位置与选中项保持;
c. 按 Android 概览键把 App 滑掉,再点开,首页状态仍在;
d. 打开开发者设置“不保留活动”,重复 c,仍能通过 restoration 恢复;
e. 在小米/华为机器上后台静置 20 min,被系统杀后重启,状态同样恢复。
把以上代码与验证流程完整讲给面试官,基本可拿到“导航/状态”维度的高分。
拓展思考
- 如果业务要求“Tab 内再嵌套底部子 Tab”(如淘宝首页的双层 Tab),StatefulShellBranch 里再嵌套一个
IndexedStack会导致 restorationId 冲突,此时需要自定义RestorationBucket的子命名空间,或者把第二层子 Tab 抽成独立 Route 树,再用goBranch的initialLocation策略控制回退栈。 - 对于 Web 端,浏览器刷新等同于进程重启,但 GoRouter 的
urlPathStrategy默认会把路由信息同步到地址栏,因此可以把“轻量状态”序列化到 query param,把“重量状态”放到 IndexedDB,实现“刷新不白屏”。 - 国内有些场景需要“微信分享后二次打开”回到指定 Tab 与页面,此时要把
go_router的redirect与Uri.parse结合起来,在redirect里读取剪贴板或 intent extra,再手动goBranch到对应分支,同时把参数写进 restorationBucket,保证分享链路+杀进程双重恢复。 - 性能优化:RestorationBucket 会在主 isolate 同步序列化,如果页面状态大于 100 KB,建议把大数据放到后台 isolate 用 hive 写磁盘,RestorationBucket 只存一个 key,重启后异步读磁盘,避免阻塞首帧。