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']
    );
  }
                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]};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With