Dart: Null-safety and retrieving values from maps

Viewed 1230

there is one thing I can't quite wrap my head around concerning null-safety in Dart, and that concerns how to safely retrieve values from Map<String,dynamic> (I've read the FAQ from the Dart docs).

Basically, the following code in the DartPad with null-safty enabled is valid:

void main() {
  int i;
  Map<String, dynamic> map = {"key": 1};
  i = map["key"];
  print(i);
}

Which I do not understand. Why can I assign map["key"] to i without the compiler shouting at me? From the docs:

Code should be safe by default. If you write new Dart code and don’t use any explicitly unsafe features, it never throws a null reference error at runtime.

But exactly this is happening. If, in the code above, the key is not in the map, or contains some random type, the program will crash on runtime, which I though is what should never happen with null safety.

I'm particular interested in this since I'm writing a Flutter app and don't understand how to properly deserialize the JSON data I fetch from the DB (try..catch? Special syntax like ??= ?). Even though I don't have the 'non-nullable' language feature enabled (I can't even write int? val without getting a warning), the compiler does not seem to mind that I assign nullable values to non-nullable variables, and will happily crash on runtime if they are null.

Basically, my question does not only concern null-safety, but the type system in general, since from my understanding it shouldn't be possible to assign a dynamic value to an int variable, but obviously this works with Map. Any explanation is greatly appreciated!

1 Answers

A dynamic variable can contain any data type, "dynamic" keyword is used when you don't know the specific data type that might be returned.

and what you're actually doing here:

i = map["key"];

is assigning a "dynamic" variable to an "int" variable and since dynamic in this case the value in the key/value pair of your Map is an integer which matches the data type "int" of variable "i" it won't crash because of type inference done at runtime and not compile time. if the "dynamic" variable was a String it would crash at runtime because of a type mismatch. Hope this is explanatory.

Related