【问题标题】:what is the slution of this error in dart?dart 中此错误的解决方案是什么?
【发布时间】: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


【解决方案1】:

您应该在 toMap 中返回 map 并在构造函数中初始化属性。

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;
    return map;
  }

  Product.fromObject(dynamic o):
    id = int.tryParse(o["id"])!,
    name = o["name"],
    description = o["description"],
    unitPrice = double.tryParse(o["unitPrice"])!;
}

【讨论】:

    猜你喜欢
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2023-03-17
    • 2021-10-12
    • 2016-06-21
    相关资源
    最近更新 更多