CamKode

Dart nested Map getter/setter

Avatar of Kosal Ang

Kosal Ang

Mon Aug 01 2022

Dart nested Map getter/setter

Get and Set your nested Map without converting them to a model mapped version. Just use the key path to go directly where you want and get, set keys and values.

Nested Map Getter

Get value from a Map by path. Use dot notation in [path] to access nessted keys. If location of path doesn't exist, it will return defaultValue.

1T? mapGetter<T>(Map map, String path, T defaultValue) {
2  List<String> keys = path.split('.');
3  String key = keys[0];
4
5  if (!map.containsKey(key)) {
6    return defaultValue;
7  }
8
9  if (keys.length == 1) {
10    return map[key] as T;
11  }
12
13  return mapGetter(map[keys.removeAt(0)], keys.join('.'), defaultValue);
14}
15
Example:
1 Map<String, dynamic> a = {
2    'a': {
3      'b': {
4        'c': {
5          'd': 'This is d',
6        },
7      }
8    }
9  };
10
11  Map<String, dynamic>? c = mapGetter<Map<String, dynamic>>(a, 'a.b.c', {});
12  String? d = mapGetter(a, 'a.b.c.d', 'no value');
13  String? e = mapGetter(a, 'a.b.c.e', 'no value');
14  print(c);
15  print(d);
16  print(e);
17
Output:
1{d: This is d}
2This is d
3no value
4

Nested Map Setter

Sets value to the Map by path. If location of path doesn't exist, it will created.

1Map<String, dynamic> mapSetter<T>(
2  Map<String, dynamic>? map,
3  String path,
4  T value,
5) {
6  List<String> keys = path.split('.');
7  String key = keys[0];
8  Map<String, dynamic> target = map ?? {};
9
10  if (keys.length == 1) {
11    return Map<String, dynamic>.from({
12      ...target,
13      key: value,
14    });
15  }
16
17  return Map<String, dynamic>.from({
18    ...target,
19    key: mapSetter(target[keys.removeAt(0)] ?? {}, keys.join('.'), value),
20  });
21}
22
Example:
1  Map<String, dynamic> a = {
2    'a': {
3      'b': {
4        'c': {
5          'd': 'This is d',
6        },
7      }
8    }
9  };
10
11  Map<String, dynamic> d = mapSetter(a, 'a.b.c.d', 'This is d modified');
12  Map<String, dynamic> e = mapSetter(d, 'a.b.c.e', 'This is e');
13  print(d);
14  print(e);
15
Output:
1{a: {b: {c: {d: This is d modified}}}}
2{a: {b: {c: {d: This is d modified, e: This is e}}}}
3

Related Posts

Creating a Heart Animation in Flutter

Creating a Heart Animation in Flutter

Animations can significantly enhance the user experience in mobile applications. One common animation is the heart (love) animation, which is often used to indicate a "like" or "favorite" action

© 2024 CamKode. All rights reserved

FacebookTwitterYouTube