【问题标题】:The parameter 'id' can't have a value of 'null' because of its type参数“id”的值不能为“null”,因为它的类型
【发布时间】:2022-07-11 23:03:59
【问题描述】:

我正在制作一个目录应用程序,我必须为项目命名,但它不起作用。

class item {
  final String id;
  final String name;
  final String desc;
  final num price;
  final String color;
  final String image;

  item({this.id, this.name, this.desc, this.price, this.color, this.image});
}

错误: {字符串 ID} 类型:字符串

参数 'id' 的值不能为 'null',因为它的类型,但隐含的默认值是 'null'。 尝试添加显式的非“null”默认值或“required”修饰符。

Full Code

【问题讨论】:

  • 这个问题是针对 Dart 还是 Kotlin 的?如果是 Dart,我建议阅读文档的这一部分以了解问题以及该问题的解决方案:dart.dev/null-safety/…

标签: flutter dart dart-null-safety


【解决方案1】:

由于您使用的是 named 参数,因此值可以为 null。您必须添加required 关键字:

class item {
  final String id;
  final String name;
  final String desc;
  final num price;
  final String color;
  final String image;

  item({required this.id, required this.name, required this.desc, required this.price, required this.color, required required this.image});
}

或者,使用? 使值可以为空:

class item {
  final String? id;
  final String? name;
  final String? desc;
  final num? price;
  final String? color;
  final String? image;

  item({this.id, this.name, this.desc, this.price, this.color, this.image});
}

【讨论】:

  • 我怎样才能使null?
  • @user8584321 这就是我的第二个选项显示的内容。您是如何阅读整个答案的?
  • 我的意思是把“?”放在哪里
  • @user8584321 你什么意思?我已将其包含在我的答案中。
  • 我的代码正在使用您的第一个代码,但我想设为 null
猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 2021-06-24
  • 2021-10-28
  • 2021-11-12
  • 2022-01-03
  • 2022-01-20
  • 2021-10-26
相关资源
最近更新 更多