You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中go_router 5.2.0在Chrome热重载页面状态丢失求助

Flutter go_router 5.2.0热重载后页面回到首页的解决方案

问题原因

热重载时,全局定义的GoRouter实例会被重新初始化,导致路由栈状态丢失,页面自动跳回初始首页。

解决方案

将GoRouter实例维护在StatefulWidget的State对象中,利用Flutter热重载时State不会被重建的特性,保留路由状态。

修改后的代码

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late final GoRouter _router;

  @override
  void initState() {
    super.initState();
    _router = GoRouter(
      initialLocation: '/',
      routes: [
        GoRoute(
          path: '/',
          name: 'homepage',
          builder: (context, state) => const MyHomePage(),
          routes: [
            GoRoute(
              path: 'shoppingcart',
              name: 'cartpage',
              pageBuilder: (context, state) => MaterialPage(
                key: state.pageKey,
                fullscreenDialog: true,
                child: const ShoppingCartScreen(),
              ),
            )
          ],
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      debugShowCheckedModeBanner: false,
      routerConfig: _router,
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("App Bar"),
          actions: [
            IconButton(
              icon: const Icon(Icons.shopping_cart),
              onPressed: () => context.pushNamed('cartpage'),
            ),
          ],
        ),
        body: Container(
          color: Colors.green[200],
          child: const Center(child: Text("Home Page")),
        ));
  }
}

class ShoppingCartScreen extends StatelessWidget {
  const ShoppingCartScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('shopping cart page'),
      ),
      body: Container(
        color: Colors.purple[200],
        child: const Center(child: Text("Shopping Cart Screen")),
      ),
    );
  }
}

原理说明

Flutter热重载仅会重建Widget树,StatefulWidget对应的State对象在无类结构变更的情况下会被保留。将GoRouter实例放在State中初始化,就能避免热重载时路由实例被重新创建,从而保留当前的路由栈状态,热重载后页面会停留在当前打开的页面。

内容的提问来源于stack exchange,提问作者jack wilson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 16:55:27