DT Dart

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 var infers a fixed type — you cannot change the type after initialization
  • Using const where final is needed — const requires compile-time constants
  • Calling methods on a nullable variable without ?. — Dart enforces null safety at compile time
  • Thinking var is the same as dynamicdynamic disables type checking; var does not

Quick check below!