Reputation: 1022
In Javascript, to conditionally add a value to an Object, I can do something like this:
const obj = {
...(myCondition && {someKey: "someValue"})
}
Can I do something similar to pass in a named parameter in Dart / Flutter? For example, if I have the below code, is there a way to conditionally pass the place
parameter only if it exists in the json
passed into the fromJson
factory function.
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']
);
}
Upvotes: 4
Views: 6248
Reputation: 908
In dart if you receive a null
object you can use double question mark operator:
What it means? : If object
is null
then take what it is after double question mark
var b = null;
var a = b ?? 'b was null, you got me!';
print(a);
result:
a: b was null, you got me!
For example:
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'] ?? [],
);
}
Null safe types are fun to use
Upvotes: 0
Reputation: 2864
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']
);
}
Upvotes: 0
Reputation: 5040
You might be looking for Dart's collection operators, specifically collection-if and collection-for capabilities.
You can, for example do something like:
final map = {
'key1': 'value1',
'key2': 'value2',
if (myCondition) 'key3': 'value3'
};
This works in lists, too:
final list = ['value1', 'value2', if (myCondition) 'value3'];
In this case, you might be after something along the lines of:
final keys = [
'id',
'displayString',
'name',
'recordType',
'collection',
'place',
'properties'
],
obj = {for (final key in keys) if (json.containsKey(key)) key: json[key]};
Upvotes: 4