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

Flutter Web中GetX路由部分页面跳转失效问题

GetX路由跳转部分页面无响应问题排查

问题描述

我有一个用于演示场景的可正常运行的仓库,不过公司项目代码因含敏感信息无法分享。当前遇到的问题是:部分页面使用Get.rootDelegate.offNamed(Routes.LISTALBUMS);跳转时完全无响应,无法进入目标页面。已尝试将相关页面改为Stateful Widget并在initState()中接收上页参数,问题依旧。但其他逻辑类似的页面使用Get.rootDelegate.offNamed(Routes.REGISTEREDMENU);却能正常跳转。

相关代码片段

main.dart

return GetMaterialApp.router(
   key: Get.key,
   useInheritedMediaQuery: true,
   debugShowCheckedModeBanner: false,
   smartManagement: SmartManagement.full,
   defaultTransition: Transition.noTransition,
   getPages: AppPages.pages,
   routerDelegate: AppRouterDelegate(),
   routeInformationParser: GetInformationParser(
     initialRoute: Routes.HOME,
   ),
);

routes.dart

class AppRouterDelegate extends GetDelegate {
  GetNavConfig get prevRoute => history.length < 2 ? history.last : history[history.length - 2];

  @override
  Future<GetNavConfig> popHistory() async {
    final result = prevRoute;
    Get.rootDelegate.offNamed(prevRoute.currentPage!.name);
    return result;
  }
  
  @override
  Widget build(BuildContext context) {
    return Navigator(
      reportsRouteUpdateToEngine: true,
      onPopPage: (route, result) => route.didPop(result),
      pages: currentConfiguration != null ? [currentConfiguration!.currentPage!] : [GetNavConfig.fromRoute(Routes.HOME)!.currentPage!],
    );
  }
}

问题排查与解决方案

1. 修复自定义路由代理的页面渲染逻辑

你自定义的AppRouterDelegate中,build方法仅渲染单个currentPage,破坏了GetX默认的路由栈管理机制。offNamed操作需要依赖完整的路由栈来完成页面替换,单页面渲染会导致路由状态异常。修改pages配置:

@override
Widget build(BuildContext context) {
  return Navigator(
    reportsRouteUpdateToEngine: true,
    onPopPage: (route, result) => route.didPop(result),
    pages: currentConfiguration?.pages ?? [GetNavConfig.fromRoute(Routes.HOME)!.currentPage!],
  );
}

2. 消除popHistory的循环调用风险

当前popHistory中调用Get.rootDelegate.offNamed会触发路由更新,可能导致循环调用。改为直接操作路由历史栈:

@override
Future<GetNavConfig> popHistory() async {
  final result = prevRoute;
  if (history.length > 1) {
    history.removeLast();
  }
  return result;
}

3. 校验目标路由的配置一致性

检查AppPages.pages中Routes.LISTALBUMS的配置,确认页面类、参数定义等是否和正常跳转的Routes.REGISTEREDMENU完全一致,避免因路由配置错误导致跳转失败。

4. 排查SmartManagement的影响

SmartManagement.full会自动销毁不在路由栈中的控制器,如果LISTALBUMS页面的控制器被提前销毁,可能导致页面无法初始化。可临时改为SmartManagement.keepFactory测试,再根据业务需求调整管理策略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:57:49