int, double, and bool.
Declaration and Type Inference
Dart is statically typed, meaning variable types are determined at compile-time. Variables can be declared using an explicit type annotation or by allowing the compiler to infer the type. Explicit Typing The type is defined explicitly by the developer.var)
The var keyword allows the compiler to determine the type based on the initialization.
- Initialized: If
varis used with an immediate value, the type is inferred and fixed. - Uninitialized: If
varis used without an immediate value, the type resolves todynamic.
Dynamic Typing
To opt out of static type checking, thedynamic keyword is used. Variables declared as dynamic can reference objects of any type, and the type of the reference can change during runtime.
Mutability and Immutability
Variables in Dart are mutable by default unless restricted by specific modifiers.Mutable Variables
Variables declared withvar or an explicit type (without final or const) are mutable. Their references can be reassigned to different objects of the same type.
Final (Runtime Constant)
Thefinal keyword declares a variable that can only be assigned once. The value can be determined at runtime (e.g., via a function return or constructor execution). Attempting to reassign a final variable results in a compile-time error.
Const (Compile-time Constant)
Theconst keyword declares a variable that must be known at compile-time. const variables are implicitly final.
- Values: Must be hardcoded literals or computed from other compile-time constants.
- Constructors: A
constconstructor enables the creation of canonicalized instances. However, the instance is only canonicalized (deduplicated in memory) if it is instantiated using theconstkeyword.
Null Safety
Dart enforces sound null safety. By default, variables are non-nullable, meaning they cannot contain the valuenull.
Non-nullable
A variable must be initialized with a non-null value before it is used.Nullable
To allow a variable to hold anull reference, append a question mark (?) to the type declaration.
Late Initialization
Thelate modifier allows the declaration of a non-nullable variable that is initialized after its declaration but before its first usage. It serves two primary technical functions:
- Deferred Initialization: The compiler treats the variable as non-nullable, but runtime checks ensure it is assigned before access.
- Lazy Evaluation: If the variable is initialized immediately with
late, the initializer expression runs only when the variable is first accessed.
Default Values
- Nullable variables: Uninitialized variables with a nullable type (e.g.,
int?) have an initial value ofnull. - Non-nullable variables: Must be initialized before use. Dart does not assign default values (like
0orfalse) to non-nullable types; failing to initialize them results in a compile-time error.
Master Dart with Deep Grasping Methodology!Learn More





