Back to quest
Dart Basics & Data TypesLevel 5 / 32

Constants: final, const, and late

Understanding immutable variables and late initialization

Not all variables need to change. Dart provides final and const for creating immutable variables, and late for variables that will be initialized later. Understanding these keywords helps you write more predictable and efficient code.

The final Keyword

The final keyword creates a variable that can only be set once. Once you assign a value to a final variable, you cannot change it. The value is determined at runtime.

Using final

example.dart
1final String username = 'alice';
2// username = 'bob'; // ❌ Error - cannot reassign
3 
4final currentTime = DateTime.now(); // Value set at runtime
5final userInput = getUserInput(); // Value from function
6 
7// final with collections
8final List<String> fruits = ['apple', 'banana'];
9fruits.add('orange'); // ✅ OK - modifying the list
10// fruits = []; // ❌ Error - cannot reassign the variable
11 
12// final without initial value (must be set before use)
13final String city;
14city = 'Paris'; // ✅ OK - first assignment
15// city = 'London'; // ❌ Error - already assigned

Hintfinal variables are initialized at runtime and cannot be reassigned. However, if the value is a collection, you can still modify the collection itself.

The const Keyword

The const keyword creates compile-time constants. These values must be known at compile time and are deeply immutable. Use const for values that will never change and are known before the program runs.

Using const

example.dart
1const double pi = 3.14159;
2const int maxUsers = 100;
3const String appName = 'MyApp';
4 
5// const with collections - deeply immutable
6const List<int> primeNumbers = [2, 3, 5, 7, 11];
7// primeNumbers.add(13); // ❌ Error - cannot modify
8// primeNumbers[0] = 1; // ❌ Error - cannot modify elements
9 
10// const requires compile-time values
11// const currentTime = DateTime.now(); // ❌ Error - not compile-time constant
12const greeting = 'Hello'; // ✅ OK - known at compile time

Hintconst creates deeply immutable, compile-time constants. The value must be known before the program runs.

The late Keyword

The late keyword is used for variables that will be initialized later but are guaranteed to have a value before they are used. This is useful for expensive initialization or when the value depends on other variables.

Using late

example.dart
1// Late variable - initialized later
2late String description;
3 
4void initialize() {
5 description = 'This is set later';
6}
7 
8void printDescription() {
9 print(description); // Must be initialized before use
10}
11 
12// Late final - can only be set once, but later
13late final String config;
14 
15void setup() {
16 config = loadConfiguration(); // Set once at runtime
17 // config = 'new value'; // ❌ Error - cannot reassign
18}
19 
20// Late with initialization
21late String heavyData = loadHeavyData(); // Only loaded when first accessed

Hintlate allows you to declare a variable that will be initialized later. If you try to use it before initialization, you'll get a runtime error.

Comparing final, const, and late

Understanding when to use each keyword is crucial for writing clean, efficient Dart code.

Comparison Example

example.dart
1// const - compile-time constant (most restrictive)
2const apiUrl = 'https://api.example.com';
3const maxRetries = 3;
4 
5// final - runtime constant (set once at runtime)
6final userId = getCurrentUserId();
7final timestamp = DateTime.now();
8 
9// late - initialized later (flexible timing)
10late final String userName;
11userName = await fetchUserName(); // Set later
12 
13// late with initialization (lazy loading)
14late String expensiveData = computeExpensiveData(); // Only computed when accessed
15 
16// Performance tip: Use const for better optimization
17const Widget icon = Icon(Icons.home); // Created once at compile-time
18final Widget icon2 = Icon(Icons.home); // Created at runtime

HintUse const for compile-time constants, final for runtime constants, and late for deferred initialization. const is most performant.

Loot collected

Key takeaways
  • Use final for variables that should only be set once at runtime
  • Use const for compile-time constants that never change
  • Use late for variables that will be initialized later
  • const is more performant than final as values are created at compile-time
  • late final combines late initialization with immutability
  • const collections are deeply immutable, final collections can be modified

Side quests

Practice exercises

1

Exercise 1: Choose the Right Keyword

Declare a variable for your birth year. Which keyword should you use?

Reveal solution
solution.dart
1const int birthYear = 2000; // Use const because your birth year never changes and is known at compile-time
2

Exercise 2: Runtime Constant

Create a variable to store the current date that should not change after being set.

Reveal solution
solution.dart
1final DateTime today = DateTime.now(); // Use final because it's set once at runtime
3

Exercise 3: Late Initialization

Create a variable that will be initialized after fetching data from an API.

Reveal solution
solution.dart
1late String userData; // Use late because it will be set after async operation
Party chat

Comments