简体   繁体   中英

Dart / Flutter Conditional Named Parameters

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]};
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']
    );
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM