Last active
January 18, 2021 08:56
-
-
Save raveesh-me/f6866ea63dde8098f68ffd39ed944555 to your computer and use it in GitHub Desktop.
Maps and Nulls
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
/// MapContainer is a class that can have an optionally null map | |
class MapContainer{ | |
final Map<String, String>? map; | |
MapContainer(this.map); | |
} | |
void main() { | |
/// dart added support to null aware subscript operator in the NNBD features update. | |
/// See: https://github.com/dart-lang/language/issues/376 | |
/// See: https://nullsafety.dartpad.dev/f6866ea63dde8098f68ffd39ed944555/ | |
/// this way, we will be able to use something like this: | |
print(MapContainer(null).map?["hello"] ?? "NA"); | |
/// In Non NNBD code, this is the best approach: | |
/// see: https://dartpad.dev/f6866ea63dde8098f68ffd39ed944555/ | |
/// when the map is null, we substitute it with empty and then use the subscripting operator | |
print((MapContainer(null).map?? {})["hello"] ?? "NA"); | |
/// when the map is empty, we still get the desired results | |
print((MapContainer({}).map?? {})["hello"] ?? "NA"); | |
/// when the map has the key, we still get the desired result. | |
print((MapContainer({"hello": "world"}).map?? {})["hello"] ?? ""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment