Why can a variable declared using 'var' be null in null-safe dart?

126 views Asked by At

I'm copying this from the docs

// In null-safe Dart, none of these can ever be null.
var i = 42; // Inferred to be an int.
String name = getFileName();
final b = Foo();

But I'm running the code below in a null-safe dartpad, and it compiles.

void main() {
  var x = null;
  print(x);
}

Is this a documentation error or am I missing something?

1

There are 1 answers

0
julemand101 On BEST ANSWER

Your example are not close to what the documentation are trying to explain. Try this instead:

void main() {
  var x = 42;
  x = null; // Error: A value of type 'Null' can't be assigned to a variable of type 'int' - line 3
  print(x);
}

The reason is that var x = 42 is "Inferred to be an int" and not int?.

In your example, what happens is that var x = null are resolved so x are seen as the type dynamic since Dart have no clue about what type you are trying to use. Since dynamic can have the value null you are good to go.