Flutter中Go Router重复点击导航失效问题求助
Go Router首次跳转正常,返回后再次点击无法跳转的解决方案
问题描述
使用Go Router实现Flutter导航时,首次点击主页的扫描按钮可正常跳转至扫描页面,但从扫描页面返回主页后,再次点击扫描按钮无法触发跳转。
问题原因
这是go_router 5.2.0版本的已知问题,该版本在路由栈处理逻辑上存在缺陷,导致重复跳转同一路径时失效。
解决方案
以下几种方式可解决该问题:
方案1:升级go_router版本
将go_router依赖升级至5.2.1及以上版本,官方已在后续版本中修复了该问题。
方案2:修改跳转方式
替换主页中使用的context.go("/scan")为以下两种方式之一:
- 使用命名路由跳转:
context.goNamed("scan");
- 使用
push方法跳转:
context.push("/scan");
修改后的homepage.dart代码示例:
import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Column( children: [ const Text("Ini Homepage", style: TextStyle(fontSize: 25)), Container( height: 50, width: double.infinity, child: ElevatedButton( onPressed: (){ // 使用命名路由跳转 context.goNamed("scan"); }, child: const Text("Scan", style: TextStyle(fontSize: 25),) ), ) ], ) ), ); } }
方案3:移除routerNeglect配置
在main.dart的GoRouter初始化中,移除routerNeglect: true配置,该配置会忽略路由历史记录的更新,可能导致重复跳转失效。
修改后的main.dart中Router配置部分:
GoRouter router = GoRouter( routes: [ GoRoute( path: "/", name: "home", builder: (context, state) => const HomePage(), routes: [ GoRoute( path: "scan", name: "scan", builder: (context, state) => const ScanPage(), ) ] ), GoRoute( path: "/login", name: "login", builder: (context, state) => const LoginPage(), ) ], initialLocation: "/", debugLogDiagnostics: true );
内容的提问来源于stack exchange,提问作者Arik setyawan
相关产品推荐
相关产品推荐

