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

创建构造器提示Non-nullable instance field 'screenHeight' must be initialized是什么意思

Dart构造器非空字段初始化报错解决方案

报错含义

你遇到的Non-nullable instance field 'screenHeight' must be initialized是Dart空安全(Null Safety)机制抛出的编译错误,含义为:非空类型的实例字段'screenHeight'必须完成初始化。

问题根因

Dart 2.12及以上版本默认开启空安全,所有未标记为可空的字段,必须在构造函数执行完之前完成初始化。你当前在构造函数的花括号内部给字段赋值的写法,属于构造函数执行阶段的后期操作,不在空安全校验认可的初始化范围内,因此会触发报错,也自然无法正常访问类实例的字段。

修复方案

以下几种方案均可解决问题,可根据你的业务场景选择:

方案1:使用初始化列表赋值(最贴合原有逻辑)

在构造函数花括号前的初始化列表阶段完成字段赋值,符合空安全校验规则:

class Variables {
  double screenWidth;
  double screenHeight;

  Variables() : 
    screenWidth = 0, 
    screenHeight = 0;

  void defaultVariables(double width, double height) {
    screenWidth = width;
    screenHeight = height;
  }
}
Variables variables = Variables();

方案2:声明字段时直接赋值(写法最简单)

如果默认值固定,直接在字段声明阶段赋值即可:

class Variables {
  double screenWidth = 0;
  double screenHeight = 0;

  Variables();

  void defaultVariables(double width, double height) {
    screenWidth = width;
    screenHeight = height;
  }
}

方案3:用late关键字标记字段

如果你确定字段会在被使用前完成赋值,可以用late关键字告知编译器由你负责字段的初始化时机:

class Variables {
  late double screenWidth;
  late double screenHeight;

  Variables() {
    screenWidth = 0;
    screenHeight = 0;
  }

  void defaultVariables(double width, double height) {
    screenWidth = width;
    screenHeight = height;
  }
}

方案4:将字段设为可空类型

如果业务允许字段为空,给类型后加?标记为可空即可:

class Variables {
  double? screenWidth;
  double? screenHeight;

  Variables() {
    screenWidth = 0;
    screenHeight = 0;
  }

  void defaultVariables(double width, double height) {
    screenWidth = width;
    screenHeight = height;
  }
}

完成以上任意一种修改后,就可以正常通过实例访问字段,比如variables.screenWidth读取对应数值。

内容的提问来源于stack exchange,提问作者Suramack

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:18:02