![](/img/trans.png)
[英]Dart/Flutter remove boilerplate parameters in named constructor to reduce code size
[英]Dart / Flutter Conditional Named Parameters
在 Javascript 中,要有条件地向对象添加值,我可以执行以下操作:
const obj = {
...(myCondition && {someKey: "someValue"})
}
我可以做一些类似于在 Dart / Flutter 中传递命名参数的事情吗? 例如,如果我有下面的代码,有没有办法有条件地传递place
参数, fromJson
是它存在于传递给fromJson
工厂函数的json
。
factory SearchResult.fromJson(Map<String, dynamic> json) {
return SearchResult(
id: json['id'],
displayString: json['displayString'],
name: json['name'],
recordType: json['recordType'],
collection: json['collection'],
place: GeoJson.fromJson(json['place']),
properties: json['properties']
);
}
您可能正在寻找 Dart 的集合运算符,特别是collection-if和collection-for功能。
例如,您可以执行以下操作:
final map = {
'key1': 'value1',
'key2': 'value2',
if (myCondition) 'key3': 'value3'
};
这也适用于列表:
final list = ['value1', 'value2', if (myCondition) 'value3'];
在这种情况下,您可能会追求以下方面的内容:
final keys = [
'id',
'displayString',
'name',
'recordType',
'collection',
'place',
'properties'
],
obj = {for (final key in keys) if (json.containsKey(key)) key: json[key]};
factory SearchResult.fromJson(Map<String, dynamic> json) {
var isNotEmpty = json['place'] != null;
return SearchResult(
id: json['id'],
displayString: json['displayString'],
name: json['name'],
recordType: json['recordType'],
collection: json['collection'],
/// This way you won't call fromJson and passing null if json['place'] is null in the first place
place: isNotEmpty ? GeoJson.fromJson(json['place']) : null,
properties: json['properties']
);
}
在 dart 中,如果您收到一个null
对象,您可以使用双问号运算符:
这是什么意思? : 如果object
为null
则取双问号后的内容
var b = null;
var a = b ?? 'b was null, you got me!';
print(a);
结果:
a: b was null, you got me!
例如:
factory SearchResult.fromJson(Map<String, dynamic> json) {
var isNotEmpty = json['place'] != null;
return SearchResult(
id: json['id'] ?? 0,
displayString: json['displayString'] ?? '',
name: json['name'] ?? '',
recordType: json['recordType'] ?? '',
collection: json['collection'] ? '',
place: GeoJson.fromJson(json['place'] ?? {}),
properties: json['properties'] ?? [],
);
}
空安全类型使用起来很有趣
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.