【发布时间】:2023-02-20 11:07:44
【问题描述】:
class Product {
int id;
String name;
String description;
double unitPrice;
Product(this.id, this.name, this.description, this.unitPrice);
Product.withId(this.id, this.name, this.description, this.unitPrice);
Future<Map<String, dynamic>> toMap() async {
var map = <String, dynamic>{};
map["name"] = name;
map["description"] = description;
map["unitPrice"] = unitPrice;
map["id"] = id;
}
Product.fromObject(dynamic o){
id = int.tryParse(o["id"])!;
name = o["name"];
description = o["description"];
unitPrice = double.tryParse(o["unitPrice"])!;
}
}
得到这样的错误:
正文可能会正常完成,导致返回“null”,但是 返回类型 'FutureOr<Map<String, dynamic>>' 是一个潜在的 不可为空的类型。
必须初始化不可为 null 的实例字段“说明”。
必须初始化不可为 null 的实例字段“id”。
必须初始化不可为 null 的实例字段“名称”。
必须初始化不可为 null 的实例字段“unitPrice”。
【问题讨论】:
-
在你的
toMap方法中你忘记了return map;,在你的Product.fromObject构造函数中你应该在初始化你的属性时使用initializer list。
标签: flutter android-studio dart