【发布时间】:2020-04-02 15:51:11
【问题描述】:
class Product {
final int id;
final String name;
// this is given value at some later stage
String downloadUrl;
Product(
this.id,
this.name,
);
factory Product.fromMap(Map data) {
// how to assign value to downloadUrl without making it static
downloadUrl = data["downloadUrl"]; // error
return Product(
data['id'],
data['name'],
);
}
}
我在创建Product 时给出id 和name,但是,我也有downloadUrl 字段,稍后将被赋予值。
问题:
在工厂构造函数中,当我得到data 时,我还需要初始化downloadUrl 字段,但我不能在工厂构造函数中这样做,因为我需要将downloadUrl 设为静态,但这超出了我的目的。然后如何从data 为其赋值?
【问题讨论】: