Skip to content

Instantly share code, notes, and snippets.

@roipeker
Last active April 3, 2020 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roipeker/48e0cc8b6e63ac7ae055b49617f156d5 to your computer and use it in GitHub Desktop.
Save roipeker/48e0cc8b6e63ac7ae055b49617f156d5 to your computer and use it in GitHub Desktop.
Dart Map::clone to make it mutable.
void main() {
const Map<String, dynamic> a = {
'value': 1,
'test': {
'asd': 'asd',
}
};
var b = a.clone(unmodifiable: false);
var c = a.clone(unmodifiable: true);
print(b);
b['test']['asd'] = '123';
b['test']['sdf'] = true;
print(b);
// error
// c['test']['asd'] = '123';
}
extension MapExt<K, V> on Map {
Map<K, V> clone({bool unmodifiable = false}) {
dynamic iterate(node) =>
node.map((k, v) => v is Map ? MapEntry(k, iterate(v)) : MapEntry(k, v));
return unmodifiable ? Map.unmodifiable(this) : iterate(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment