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

Dart空安全(Null Safety)下命名参数构造器创建报错如何解决?

问题原因

Dart 2.12+ 启用空安全后,命名参数默认是可选参数,如果你没有给参数标记required、也没有设置默认值,参数对应传递的属性必须为可空类型,否则实例化时如果不传参数,非空属性会被赋值为null,违反空安全校验规则,所以触发报错。

解决方案

你可以根据业务场景选择以下任意一种方案修复:

  • 方案1:要求构造器调用时必须传入所有参数,给所有命名参数加required修饰
void main() {
  
}

class Student {
  String name = '';
  num age = 0;
  List<num> marks = [];
  
  Student({
    required this.name,
    required this.age,
    required this.marks
    });
  
  void printStudentDetails() {
    print('Student Name: ' + this.name);
  }
}
  • 方案2:允许参数不传,给构造参数设置和类属性匹配的默认值,默认值需要是编译时常量,所以列表类型默认值需要加const修饰
void main() {
  
}

class Student {
  String name = '';
  num age = 0;
  List<num> marks = [];
  
  Student({
    this.name = '',
    this.age = 0,
    this.marks = const []
    });
  
  void printStudentDetails() {
    print('Student Name: ' + this.name);
  }
}
  • 方案3:属性本身允许为空的场景,把属性类型修改为可空类型,使用属性时提前判空即可
void main() {
  
}

class Student {
  String? name;
  num? age;
  List<num>? marks;
  
  Student({
    this.name,
    this.age,
    this.marks
    });
  
  void printStudentDetails() {
    print('Student Name: ' + (this.name ?? '未设置'));
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 17:30:04