# FlutterError: 在 InheritedWidget 上下文中未找到 'const' 键

- **ID:** `flutter/const-key-not-found`
- **领域:** flutter
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 75%

## 根因

小部件使用 const 键访问 InheritedWidget，但该 InheritedWidget 不在访问小部件上方的 widget 树中，通常是由于缺少 provider 或构建上下文不正确。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Flutter 3.10.0 | active | — | — |
| Flutter 3.19.0 | active | — | — |
| Dart 3.0.0 | active | — | — |

## 解决方案

1. ```
   确保 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。
   ```
2. ```
   验证用于访问 InheritedWidget 的 BuildContext 来自后代小部件。仅在 InheritedWidget 已插入树后调用 'context.dependOnInheritedWidgetOfExactType'，例如在子小部件的 build 方法中。
   ```
3. ```
   使用 Provider 包（如 Riverpod）自动管理 InheritedWidget，确保正确放置。
   ```

## 无效尝试

- **Replace const key with a non-const key using a random value** — The issue is not the const qualifier but the InheritedWidget's absence; changing the key doesn't fix the missing ancestor. (80% 失败率)
- **Wrap the entire app in a MaterialApp to provide default InheritedWidgets** — MaterialApp provides MediaQuery and Theme, but the error is about a custom InheritedWidget; MaterialApp won't supply it. (60% 失败率)
- **Add a dummy InheritedWidget at the root with a const key** — The dummy widget doesn't provide the required data; the accessing widget still fails to find the correct InheritedWidget. (90% 失败率)
