Junior
What is the difference between var and dynamic in Dart?
sobes.tech AI
Answer from AI
var defines a variable whose type is automatically set based on the assigned value and remains fixed. dynamic defines a variable whose type can change during program execution.
| Property | var |
dynamic |
|---|---|---|
| Type Binding | During compilation (static) | During runtime (dynamic) |
| Type Change | Impossible after initialization | Possible at any time |
| Type Checking | Performed at compile time | Performed at runtime |
| Performance | Optimal | May be slightly lower due to run-time checks |
Example of using var:
// Type x is defined as int at compile time
var x = 10;
// The following line will cause a compile error,
// because type of x is already defined as int
// x = "hello";
Example of using dynamic:
// Type y can change during runtime
dynamic y = 10;
// y is now of type String
y = "hello";
// y is now of type bool
y = true;
Using var is preferable when the type of the variable is known in advance, as it provides type safety and better performance. dynamic should be used only when the type is truly unknown until runtime (e.g., when working with JSON or reflection), but this can lead to runtime errors if operations are performed on a value of an incompatible type.