Search code examples
dartdart-null-safety

Difference between Object, Dynamic and Var in Dart?


There is a discussion about dynamic and var before null-safety. Then what's the Object? between each of them?

  1. Is Object? == dynamic?
  2. How about var? and dynamic??
  3. Any difference between dynamic? and dynamic?

I see the official document about null-safety, but can't find the related topic.


Solution

    1. dynamic is a special type that disables static type-checking. You can attempt to call any method on a dynamic type. If the object turns out not to have such a method, then it will result in a runtime failure instead of a compile-time one.

      Object? is a base type suitable for referencing any object, including null. Unlike dynamic, it is statically type-checked, so you would get compile-time failures if you attempt to call most methods on it without explicitly checking the runtime type or without performing a cast.

    2. var? is not valid syntax. var is not a type; it declares a variable without explicitly specifying a type, allowing the type to be inferred.

      dynamic? is valid but is redundant. (See #3.)

    3. Variables of type dynamic can already include null, so adding a ? to make it nullable is redundant. The Dart analyzer will tell you so.