Dart: Variables & Data Types
What you will learn
How to declare variables with explicit types or var, the difference between final and const, and Dart's type-safety model.
Dart is statically typed — every variable has a known type at compile time. You can write the type explicitly or let var infer it.
String name = 'Alice'; // explicit type
var age = 25; // inferred int
double height = 5.6;
bool isStudent = true;
Type inference with var
var tells Dart to infer the type from the initial value. The type is still fixed — you cannot assign a string to a var variable that was inferred as int.
var message = 'Hello'; // inferred as String
var count = 42; // inferred as int
// count = 'hello'; // compile error!
final (runtime constant) vs const (compile-time constant)
final greeting = 'Hello'; // set once, at runtime
const pi = 3.14159; // compile-time constant
final now = DateTime.now(); // OK — runtime value
// const now = DateTime.now(); // Error — not compile-time constant
Use final for values you set once that you cannot determine at compile time (like current time or API results). Use const for values known at compile time.
Null safety (Dart 3+)
Dart has sound null safety. Types are non-nullable by default. Add ? to allow null:
String? nullableName; // can be null
String nonNull = 'Alice'; // cannot be null
// nonNull = null; // compile error
Common mistakes
- Forgetting that
varinfers a fixed type — you cannot change the type after initialization - Using
constwherefinalis needed —constrequires compile-time constants - Calling methods on a nullable variable without
?.— Dart enforces null safety at compile time - Thinking
varis the same asdynamic—dynamicdisables type checking;vardoes not
Quick check below!