我有一个如下的代码。它启动Model
的一个实例。有一些像json['status']
这样的值可以是null
。给它们一个默认值''
的最佳方式是什么?我来自javascript世界,所以我正在寻找一种类似json['status'] || ''
的方式。
factory Model.fromJson(Map<String, dynamic> json) {
return Model(
id: json['id'],
status: json['status'],
amount: json['amount'],
scheme: json['scheme'],
type: json['type']);
}
我们可以如下使用空合并(??
(运算符:
factory Model.fromJson(Map<String, dynamic> json) {
return Model(
id: json['id'] ?? 0,
status: json['status'] ?? 'status',
amount: json['amount'] ?? 0,
scheme: json['scheme'] ?? 'scheme',
type: json['type'] ?? 'defaultType');
}
你也可以在官方的Dart备忘单中阅读更多关于null感知运算符的信息。