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

Flutter中在State构造器读取传递变量时触发空检查运算符错误

问题原因与解决方法

为什么构造器里访问widget.dvariable会报错?

State类的构造器执行时,Flutter框架还没把对应的StatefulWidget实例绑定到State的widget属性上,此时widget是null,访问widget.dvariable自然会触发「Null check operator used on a null value」错误。而build方法是在State与Widget完成绑定后才会调用,所以能正常读取变量。

正确的访问方式

用State生命周期里的initState方法代替构造器,这是第一个可以安全访问widget的生命周期方法,它会在State对象被插入到Widget树时调用,且仅执行一次:

修改后的_DPageState代码:

class _DPageState extends State<DPage> {
  @override
  void initState() {
    super.initState();
    // 这里可以安全访问widget的属性
    print(widget.dvariable);
  }

  @override
  Widget build(BuildContext context) {
    return Container(child: Text(widget.dvariable));
  }
}

额外优化建议

给StatefulWidget的参数指定类型并设为final,避免动态类型带来的潜在问题,让代码更严谨:

class DPage extends StatefulWidget {
  final String dvariable;
  DPage(this.dvariable);
  @override
  State<DPage> createState() => _DPageState();
}

内容的提问来源于stack exchange,提问作者tired and bored dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:54:18