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

使用GoRouter时,Flutter实现全局Dialog及解决navigatorKey空值问题

解决GoRouter下navigatorKey.currentContext为null的弹窗问题

问题根源

你定义的navigatorKey没有和GoRouter的Navigator实例绑定,导致currentContext始终为null。使用MaterialApp.router时,全局导航key不会自动关联到GoRouter内部的Navigator,必须手动配置。

修复方案

方案1:绑定navigatorKey到GoRouter

在初始化GoRouter的地方,将全局navigatorKey传入配置:

GoRouter(
  navigatorKey: navigatorKey, // 关联全局导航key
  routes: [
    // 你的路由列表配置
  ],
)

这样navigatorKey就能正确关联到GoRouter的Navigator,currentContext就不会再为null。

方案2:直接使用BlocListener的上下文弹窗

不需要依赖全局navigatorKey,直接用BlocListener回调里的context即可,这个上下文属于MaterialApp内部层级,能直接访问Navigator:

BlocListener<InactivityCubit, InactivityState>(
  listener: (context, state) => state.whenOrNull(
    showDialog: () {
      AmazingDialog.show(context); // 直接使用当前listener的context
      return null;
    },
  ),
  child: widget,
)

这种方式更简洁,也避免了全局key可能带来的生命周期问题。

注意事项

如果坚持使用全局navigatorKey,要确保在调用navigatorKey.currentContext之前,GoRouter的Navigator已经完成初始化(不要在App启动的同步代码中立即调用)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:07:17