Variables and Built-in Types
Declaring variables with var, final, and const, and Dart's core built-in types — and why the difference between them matters.
3 min de lectura
Dart gives you three keywords for declaring a variable — var, final, and const — and picking the right one communicates intent, not just style.
var and type inference
var name = 'Ada'; // inferred as String
var age = 36; // inferred as int
var pi = 3.14159; // inferred as doublevar doesn't mean "no type" — it means "figure out the type from the value on the right, once, and enforce it from then on." After the line above runs, name is a String forever; name = 42 is a compile error, not a runtime surprise. This is the core of what makes Dart statically typed even when you rarely write a type name yourself.
You can still write the type explicitly when it helps readability:
String city = 'Phnom Penh';
int population = 2_300_000; // underscores are allowed as digit separators
double temperature = 31.5;
bool isCapital = true;final vs const
Both prevent reassignment, but they differ in when the value is fixed:
final now = DateTime.now(); // set once, at runtime — value known only when this line runs
const maxUsers = 100; // fixed at compile time — must be a constant expressionfinal DateTime.now() is legal because the value only needs to be known once, when that line executes. const DateTime.now() would fail to compile, because const requires the value to be computable before the program even runs — a literal, or an expression built entirely from other const values.
A practical rule: default to final for anything you compute once and never reassign (which should be most of your variables). Reach for const specifically for values you know ahead of time, like configuration numbers or fixed strings — the compiler can optimize them more aggressively, and in Flutter, const widgets skip being rebuilt entirely.
Built-in types
Dart's core types cover the basics you'd expect:
int count = 10; // whole numbers
double price = 9.99; // decimal numbers
num anything = 5; // int or double — a shared supertype
String label = 'total'; // text
bool isValid = false; // true or falsenum is worth knowing about even though you'll reach for int or double most of the time — it's the common parent type when a value could reasonably be either, like the result of a calculation that mixes both.
A first taste of null safety
By default, none of these variables can hold null — String label = null; is a compile error. If a variable genuinely might have no value, you say so explicitly with a ?:
String? nickname; // allowed to be null, and starts out nullThis is Dart's sound null safety, and it's a big enough topic that it gets its own dedicated lesson later. For now, the takeaway is simple: a type without ? is a promise that a value is always there, and the compiler holds you to it.