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

使用GetX定时检查路由时ModalRoute.of(Get.context!)返回null求助

解决GetX定时检查当前路由的问题

核心问题原因

你之前用ModalRoute.of(Get.context!)拿不到路由,是因为Get.context不一定对应当前活跃路由的上下文,路由切换后旧上下文和新路由脱钩,自然返回null;而build方法里的context绑定的是初始路由的上下文,切换路由后不会更新,所以始终指向初始路由。

最优解决方案:用GetX自带的路由API

GetX的导航管理器已经维护了当前路由信息,直接用Get.currentRoute就能获取当前路由名称,完全不需要依赖context,代码更简洁可靠:

Timer? checkRouteTimer;

// 初始化定时器
checkRouteTimer = Timer.periodic(const Duration(seconds: 15), (timer) {
  if (Get.currentRoute == "/first") {
    // 在这里执行你的业务逻辑
  }
});

注意事项:避免内存泄漏

定时器一定要在页面销毁或控制器关闭时取消,防止内存泄漏:

1. 在GetxController中使用的情况

class MyController extends GetxController {
  Timer? checkRouteTimer;

  @override
  void onInit() {
    super.onInit();
    // 启动定时器
    checkRouteTimer = Timer.periodic(const Duration(seconds: 15), (timer) {
      if (Get.currentRoute == "/first") {
        // 执行逻辑
      }
    });
  }

  @override
  void onClose() {
    // 关闭控制器时取消定时器
    checkRouteTimer?.cancel();
    super.onClose();
  }
}

2. 在StatefulWidget中使用的情况

class MyPage extends StatefulWidget {
  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  Timer? checkRouteTimer;

  @override
  void initState() {
    super.initState();
    checkRouteTimer = Timer.periodic(const Duration(seconds: 15), (timer) {
      if (Get.currentRoute == "/first") {
        // 执行你的逻辑
      }
    });
  }

  @override
  void dispose() {
    // 页面销毁时取消定时器
    checkRouteTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Container());
  }
}

为什么这个方案更好

Get.currentRoute是GetX导航栈直接维护的状态,不管路由怎么切换,都能实时返回当前活跃的路由名称,完全绕开了context的各种坑,代码也更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:10:23