我希望创建一个稍后可以引用的自定义模型:该模型只是国家/地区及其指标的列表。创建模型后,我想访问它,类似于: 国家('au').人口
我已经创建了下面的类,但是除此之外,我不确定如何使用数据初始化模型。我认为我需要一张国家/地区实例 map ?
class Country {
final String code;
final String name;
final int population;
Country({
this.code,
this.name,
this.population,
});
Map Countries = {'au': new Country('code': 'au', 'name': 'Australia', population: 25000000),
'uk': new Country('code': 'uk', 'name': 'United Kingdom', 'population': 66000000)}
}
最佳答案
您应该使用工厂构造函数来初始化您的类,并将所有模型放在静态方法中。
class Country {
final String code;
final String name;
final int population;
Country._({
this.code,
this.name,
this.population,
});
factory Country(String code) => countries[code];
static final countries = {
'au': Country._(code: 'au', name: 'Australia', population: 25000000),
'uk': Country._(code: 'uk', name: 'United Kingdom', population: 66000000)
};
}
那么你可以这样做:
var population = Country('au').population; //Returns null if the code is not defined in the map.
注意:您的代码甚至无法编译,因为参数名称不需要定义为字符串。
关于dart - 在 Dart 中创建自定义模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62255471/