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

Flutter从杀死状态通过DeepLink启动时出现GlobalKey重复使用错误

问题描述

我用GlobalKey打开侧边抽屉(end drawer),但当应用处于杀死状态时通过DeepLink启动应用,会出现以下错误:

A GlobalKey was used multiple times inside one widget's child list.
The offending GlobalKey was:
[LabeledGlobalKey<NavigatorState>#53296 Key Created by default]
The parent of the widgets with that key was:
FocusInheritedScope
The first child to get instantiated with that key became:
Navigator- [LabeledGlobalKey<
NavigatorState>#53296 Key
Created by default]
The second child that was to be instantiated with that key was:
_FocusInheritedScope
A GlobalKey can only be specified on one widget at a time in the widget tree.

我试过在3个页面用同一个GlobalKey实例,也试过用不同的GlobalKey,但问题还是没解决。

解决方案

1. 确保GlobalKey全局唯一且初始化正确

不要在页面内部初始化GlobalKey,而是在全局级别(比如main()函数外、独立全局类)创建唯一实例,避免页面重建时重复生成相同key:

// 全局唯一的侧边栏GlobalKey实例
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        key: _scaffoldKey,
        endDrawer: const Drawer(),
        // 其他页面内容
      ),
    );
  }
}

2. 处理DeepLink冷启动的Widget树冲突

DeepLink冷启动时,Flutter可能重复挂载部分Widget导致key冲突。可以在MaterialApp的路由逻辑中,确保Scaffold的key仅被赋值一次:

MaterialApp(
  onGenerateRoute: (settings) {
    // 处理DeepLink路由
    if (settings.name == '/target-deep-link') {
      return MaterialPageRoute(
        builder: (context) => Scaffold(
          key: _scaffoldKey,
          endDrawer: const Drawer(),
          body: const DeepLinkTargetPage(),
        ),
      );
    }
    return MaterialPageRoute(builder: (context) => const HomePage());
  },
);

3. 手动指定Navigator的GlobalKey

错误提示中的key是默认Navigator的LabeledGlobalKey,可手动给Navigator分配唯一GlobalKey替代默认值:

final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();

MaterialApp(
  navigatorKey: _navigatorKey,
  // 其他配置项
);

4. 排查Widget树的重复key引用

检查所有使用GlobalKey的位置,确保同一层级Widget中没有重复使用同一key,包括嵌套结构里的父、子Widget,避免FocusInheritedScope这类内部组件和Navigator的key产生冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:15:06