As I understand, for static types, data types are known at compile-time and for dynamic types, data types are known/evaluated at run-time.
The Dart document (https://dart.dev/faq#q-is-dart-a-statically-typed-language) says that dart is a statically typed language -
Q. Is Dart a statically typed language?
Yes, Dart 2 is statically typed. For more information, read about Dart’s type system.
With its combination of static and runtime checks, Dart has a sound type system, which guarantees that an expression of one type cannot produce a value of another type. No surprises!
Even with type-safe Dart, you can annotate any variable with dynamic if you need the flexibility of a dynamic language. The dynamic type itself is static but can contain any type at runtime. Of course, that removes many of the benefits of a type-safe language for that variable.
So then how are we able to assign a variable "dynamic" data type, which leaves the type evaluation at run-time?
CodePudding user response:
The short answer is that dynamic
is a type on its own. It just moves the type-checking to runtime (as referred to in the text you quoted).
This lets you do things like final Map<String, dynamic> json = await fetchData();
, which would not be possible otherwise.
Note that using the dynamic
type is strongly discourage by Dart, specifically because of its runtime impact and lack of "staticness".
CodePudding user response:
The dynamic is one of the types.
So, if you want to use a dynamic variable, you have to cast it another types.