Flutter 继承InheritedWidget存储GlobalKey时出现Null check空值错误如何解决
错误根因
你遇到的「Null check operator used on a null value」错误,核心触发点是KeysToBeInherited.of()方法中用!强制解包可空变量时,context.dependOnInheritedWidgetOfExactType<KeysToBeInherited>()返回了空值,空值强制解包直接触发报错。
返回空值的常见场景有两种:
- 调用
KeysToBeInherited.of()时传入的context所在的Widget树,没有被KeysToBeInherited组件包裹,找不到对应的父级InheritedWidget实例 - 在
KeysToBeInherited的父级上下文中调用of方法,此时KeysToBeInherited还没被挂载到当前Widget树中,自然无法匹配到实例
修复方案
1. 新增空校验抛出明确错误(推荐)
修改of方法的实现,解包前先做非空判断,给出可读性更高的错误提示,避免默认空检查报错难以定位问题:
static KeysToBeInherited of(BuildContext context) { final KeysToBeInherited? result = context.dependOnInheritedWidgetOfExactType<KeysToBeInherited>(); if (result == null) { throw FlutterError( 'KeysToBeInherited.of() called with a context that does not contain a KeysToBeInherited.\n' 'Please confirm you have wrapped the target widget tree with KeysToBeInherited, and the used context is a child of the KeysToBeInherited node.', ); } return result; }
2. 校验InheritedWidget的挂载层级
必须保证调用of方法的context属于KeysToBeInherited的子节点,正确的使用示例如下:
// 上层节点挂载KeysToBeInherited,包裹所有需要访问共享Key的子节点 void main() { runApp( KeysToBeInherited( add: GlobalKey(), card: GlobalKey(), color: GlobalKey(), bepy: GlobalKey(), me: GlobalKey(), publish: GlobalKey(), child: const MyApp(), ), ); } // 子节点中调用of方法,此时context是KeysToBeInherited的后代上下文,可以正常获取实例 class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { final inheritedKeys = KeysToBeInherited.of(context); // 正常使用inheritedKeys.add等全局Key return const SizedBox.shrink(); } }
不要在和KeysToBeInherited同级的context,或是KeysToBeInherited的父级context中调用of方法,这两种情况都无法匹配到实例
3. 改为可空返回适配特殊场景
如果你的业务场景允许部分节点获取不到KeysToBeInherited实例,可以直接修改of方法返回可空类型,由使用方自行处理空逻辑:
static KeysToBeInherited? of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<KeysToBeInherited>(); }
使用时用?.调用属性即可,避免空安全错误。
内容的提问来源于stack exchange,提问作者dillivijay v
相关产品推荐
相关产品推荐

