Flutter报The type parameter is not nullable: null错误解决方法
错误产生原因
该错误由Dart空安全类型校验直接触发:
Future<T>.delayed构造函数的第二个参数为可选的返回值生成回调,当不传入该回调时,延迟结束后Future的默认返回值为null- 代码中声明该延迟Future的泛型为非空类型
int,非空类型不允许接收null值,因此直接抛出The type parameter is not nullable: null错误。
修复方法
你当前代码中调用延迟方法仅为实现3秒等待效果,不需要获取int类型的返回值,只需要修正泛型声明即可解决核心报错,将原报错行:
await Future<int>.delayed(Duration(seconds: 3));
替换为以下任意一种合法写法:
// 不指定泛型,由编译器自动推导类型 await Future.delayed(const Duration(seconds: 3)); // 明确指定泛型为void,标识该延迟不需要返回任何值 await Future<void>.delayed(const Duration(seconds: 3));
额外注意事项
现有代码还存在两个潜在运行时问题,建议同步修复:
- 常量构造函数前建议加
const修饰符提升性能,避免不必要的对象重建 - 延迟等待期间如果用户手动关闭页面、组件被销毁,后续调用
Navigator.pop会触发上下文不存在的报错,需要在执行pop前增加组件挂载状态校验:
Future<dynamic> createSomething() async { showDialog( context: context, builder: (BuildContext context) => const Center( child: CircularProgressIndicator(), ), ); await Future.delayed(const Duration(seconds: 3)); // 组件已销毁时直接返回,不执行后续操作 if (!mounted) return; Navigator.of(context, rootNavigator: true).pop(); }
- 如果你确实需要延迟返回int类型结果,必须传入第二个回调参数返回合法的int值,例如:
// 延迟3秒后返回int值200,不会触发空类型错误 final int result = await Future<int>.delayed( const Duration(seconds: 3), () => 200, );
内容的提问来源于stack exchange,提问作者nick coder
相关产品推荐
相关产品推荐

