FlutterError: 在 InheritedWidget 上下文中未找到 'const' 键
FlutterError: 'const' key not found in InheritedWidget context
ID: flutter/const-key-not-found
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Flutter 3.10.0 | active | — | — | — |
| Flutter 3.19.0 | active | — | — | — |
| Dart 3.0.0 | active | — | — | — |
根因分析
小部件使用 const 键访问 InheritedWidget,但该 InheritedWidget 不在访问小部件上方的 widget 树中,通常是由于缺少 provider 或构建上下文不正确。
English
A widget used a const key to access an InheritedWidget, but the InheritedWidget was not in the widget tree above the accessing widget, often due to missing provider or incorrect build context.
官方文档
https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html解决方案
-
确保 InheritedWidget 位于访问小部件上方的 widget 树中。例如,使用 provider 包装相关子树: class MyProvider extends InheritedWidget { final String data; MyProvider({required this.data, required Widget child}) : super(child: child); static MyProvider of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<MyProvider>()!; } @override bool updateShouldNotify(MyProvider oldWidget) => data != oldWidget.data; } 然后在访问之前在 build 方法中使用 MyProvider。 -
验证用于访问 InheritedWidget 的 BuildContext 来自后代小部件。仅在 InheritedWidget 已插入树后调用 'context.dependOnInheritedWidgetOfExactType',例如在子小部件的 build 方法中。
-
使用 Provider 包(如 Riverpod)自动管理 InheritedWidget,确保正确放置。
无效尝试
常见但无效的做法:
-
Replace const key with a non-const key using a random value
80% 失败
The issue is not the const qualifier but the InheritedWidget's absence; changing the key doesn't fix the missing ancestor.
-
Wrap the entire app in a MaterialApp to provide default InheritedWidgets
60% 失败
MaterialApp provides MediaQuery and Theme, but the error is about a custom InheritedWidget; MaterialApp won't supply it.
-
Add a dummy InheritedWidget at the root with a const key
90% 失败
The dummy widget doesn't provide the required data; the accessing widget still fails to find the correct InheritedWidget.