Last active
April 3, 2020 16:25
-
-
Save roipeker/48e0cc8b6e63ac7ae055b49617f156d5 to your computer and use it in GitHub Desktop.
Dart Map::clone to make it mutable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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