Skip to main content
A typed variable in Dart represents a named memory allocation strictly bound to a specific data type during compile-time. Because Dart utilizes a sound static type system, once a variable is bound to a type—either through explicit declaration or analyzer type inference—it cannot be reassigned to a value of a non-subtype, guaranteeing type safety at runtime.

Syntax

// Explicit non-nullable type declaration
Type identifier = expression;

// Explicit nullable type declaration
Type? identifier = expression;

// Type inference (statically typed via the initializer)
var identifier = expression;

Type Declaration Mechanisms

Dart provides multiple mechanisms for establishing a variable’s type: 1. Explicit Typing The developer explicitly defines the data type preceding the variable identifier. The compiler enforces this type strictly.
int counter = 0;
String identifier = "System_01";
bool isActive = true;
2. Type Inference Using the var, final, or const keywords without an explicit type annotation instructs the Dart analyzer to infer the static type based on the initialization value. The variable remains strictly typed.
var threshold = 10.5;      // Statically inferred as double
final username = "admin";  // Statically inferred as String
const maxRetries = 3;      // Statically inferred as int
3. Dynamic Typing (Type System Opt-Out) The dynamic keyword explicitly disables static type checking for a variable, deferring type resolution to runtime. This allows the variable to hold values of any type and change types during execution.
dynamic payload = "Initial String";
payload = 404; // Valid at runtime

Sound Null Safety

Dart’s type system distinguishes between nullable and non-nullable types. By default, all typed variables are non-nullable and must be initialized before use. To declare a variable that can legally hold a null value, the type annotation must be suffixed with a question mark (?).
// Non-nullable (cannot hold null)
String sessionToken = "abc-123";

// Nullable (can hold a String or null)
String? optionalParameter = null;

Generics in Typed Collections

When declaring typed variables for collections, Dart uses generics (<T>) to enforce the type of the elements contained within the collection.
// Explicitly typed List containing integers
List<int> byteStream = [0, 1, 1, 0];

// Explicitly typed Map with String keys and dynamic values
Map<String, dynamic> jsonPayload = {
  "id": 101,
  "status": "active"
};
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More