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

使用go_router跳转后返回,Page1页面状态丢失问题

go_router页面重定向后ListView滚动状态丢失的解决方法

问题场景

在Android、Web、Windows平台使用go_router包,升级依赖后出现以下问题:

  • 启动应用,联网状态下进入首页,将包含100项的ListView滚动至第50项
  • 关闭网络后,通过路由重定向跳转至无网络页面
  • 重新联网返回首页时,ListView回到初始顶部位置,未恢复之前的滚动位置

依赖版本示例

flutter:
  sdk: flutter
go_router: ^12.1.3
connectivity_plus: ^5.0.1

复现代码

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:connectivity_plus/connectivity_plus.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;
  bool _hasNetwork = true;

  @override
  void initState() {
    super.initState();
    _checkNetwork();
    Connectivity().onConnectivityChanged.listen((result) {
      setState(() {
        _hasNetwork = result != ConnectivityResult.none;
      });
    });

    _router = GoRouter(
      routes: [
        GoRoute(
          path: '/',
          builder: (context, state) => const HomePage(),
        ),
        GoRoute(
          path: '/no-network',
          builder: (context, state) => const NoNetworkPage(),
        ),
      ],
      redirect: (context, state) {
        if (!_hasNetwork && state.location != '/no-network') {
          return '/no-network';
        }
        if (_hasNetwork && state.location == '/no-network') {
          return '/';
        }
        return null;
      },
    );
  }

  void _checkNetwork() async {
    final result = await Connectivity().checkConnectivity();
    setState(() {
      _hasNetwork = result != ConnectivityResult.none;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      title: 'Flutter Demo',
      routerConfig: _router,
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('首页')),
      body: ListView.builder(
        itemCount: 100,
        itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('无网络')),
      body: const Center(child: Text('请检查网络连接')),
    );
  }
}

问题原因

路由重定向时,原首页会被从路由栈中移除或替换,返回首页时会重新构建HomePage组件,导致ListView的滚动状态被重置。

解决方案

方案1:使用StatefulShellRoute保持页面状态

通过StatefulShellRoute.indexedStack将首页和无网络页面纳入同一个导航容器,切换页面时不会销毁原有页面,自动保留滚动状态:

// 修改路由配置部分
_router = GoRouter(
  routes: [
    StatefulShellRoute.indexedStack(
      builder: (context, state, navigationShell) {
        return Scaffold(body: navigationShell);
      },
      branches: [
        StatefulShellBranch(
          routes: [
            GoRoute(
              path: '/',
              builder: (context, state) => const HomePage(),
            ),
          ],
        ),
        StatefulShellBranch(
          routes: [
            GoRoute(
              path: '/no-network',
              builder: (context, state) => const NoNetworkPage(),
            ),
          ],
        ),
      ],
    ),
  ],
  redirect: (context, state) {
    if (!_hasNetwork && state.location != '/no-network') {
      return '/no-network';
    }
    if (_hasNetwork && state.location == '/no-network') {
      return '/';
    }
    return null;
  },
);

方案2:手动保存/恢复滚动位置

将HomePage改为StatefulWidget,使用ScrollController手动记录滚动位置,在页面初始化时恢复:

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final ScrollController _scrollController = ScrollController();
  double _savedOffset = 0.0;

  @override
  void initState() {
    super.initState();
    // 页面构建完成后恢复滚动位置
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_savedOffset > 0) {
        _scrollController.jumpTo(_savedOffset);
      }
    });
  }

  @override
  void dispose() {
    // 销毁前保存当前滚动位置
    _savedOffset = _scrollController.offset;
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('首页')),
      body: ListView.builder(
        controller: _scrollController,
        itemCount: 100,
        itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
      ),
    );
  }
}

方案3:结合PageStorageKey辅助恢复

给ListView添加唯一的PageStorageKey,让Flutter的PageStorage自动保存滚动状态(需确保页面重建时key不变):

ListView.builder(
  key: const PageStorageKey('home_list_view'),
  itemCount: 100,
  itemBuilder: (context, index) => ListTile(title: Text('Item $index')),
)

注:此方案依赖PageStorage的全局存储,若页面被完全移除出路由栈,存储的状态可能被清除,建议结合方案2使用。

内容的提问来源于stack exchange,提问作者Zia Ur Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 07:01:10