dart - 在 Dart 中创建自定义模型

标签 dart

我希望创建一个稍后可以引用的自定义模型:该模型只是国家/地区及其指标的列表。创建模型后,我想访问它,类似于: 国家('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/

相关文章:

flutter - flutter 的蓝色json值被切断

flutter - 如何在回调函数中产生?

json - Flutter 获取 Object 属性名称

dom - 谷歌 Dart : change event for IListElement

dart - Flutter:Tabbar 与 BottomNavigationBar

flutter - 将字符串传递给 Flutter 中的类?

android - 向下滚动时隐藏的 Flutter TabBar 和 SliverAppBar

angular - 我可以在可注入(inject)类中有一个通用方法吗?

sqlite - 插入sqlite flutter 而不卡住界面

flutter - 随手上传文件,显示缩略图