Skip to content

Instantly share code, notes, and snippets.

@raveesh-me
Last active January 18, 2021 08:56
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 raveesh-me/f6866ea63dde8098f68ffd39ed944555 to your computer and use it in GitHub Desktop.
Save raveesh-me/f6866ea63dde8098f68ffd39ed944555 to your computer and use it in GitHub Desktop.
Maps and Nulls
/// 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