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
1final String username = 'alice';2// username = 'bob'; // ❌ Error - cannot reassign3 4final currentTime = DateTime.now(); // Value set at runtime5final userInput = getUserInput(); // Value from function6 7// final with collections8final List<String> fruits = ['apple', 'banana'];9fruits.add('orange'); // ✅ OK - modifying the list10// fruits = []; // ❌ Error - cannot reassign the variable11 12// final without initial value (must be set before use)13final String city;14city = 'Paris'; // ✅ OK - first assignment15// city = 'London'; // ❌ Error - already assignedHintfinal 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
1const double pi = 3.14159;2const int maxUsers = 100;3const String appName = 'MyApp';4 5// const with collections - deeply immutable6const List<int> primeNumbers = [2, 3, 5, 7, 11];7// primeNumbers.add(13); // ❌ Error - cannot modify8// primeNumbers[0] = 1; // ❌ Error - cannot modify elements9 10// const requires compile-time values11// const currentTime = DateTime.now(); // ❌ Error - not compile-time constant12const greeting = 'Hello'; // ✅ OK - known at compile timeHintconst 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
1// Late variable - initialized later2late String description;3 4void initialize() {5 description = 'This is set later';6}7 8void printDescription() {9 print(description); // Must be initialized before use10}11 12// Late final - can only be set once, but later13late final String config;14 15void setup() {16 config = loadConfiguration(); // Set once at runtime17 // config = 'new value'; // ❌ Error - cannot reassign18}19 20// Late with initialization21late String heavyData = loadHeavyData(); // Only loaded when first accessedHintlate 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
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 later12 13// late with initialization (lazy loading)14late String expensiveData = computeExpensiveData(); // Only computed when accessed15 16// Performance tip: Use const for better optimization17const Widget icon = Icon(Icons.home); // Created once at compile-time18final Widget icon2 = Icon(Icons.home); // Created at runtimeHintUse 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
Exercise 1: Choose the Right Keyword
Declare a variable for your birth year. Which keyword should you use?
Reveal solutionHide solution
1const int birthYear = 2000; // Use const because your birth year never changes and is known at compile-timeExercise 2: Runtime Constant
Create a variable to store the current date that should not change after being set.
Reveal solutionHide solution
1final DateTime today = DateTime.now(); // Use final because it's set once at runtimeExercise 3: Late Initialization
Create a variable that will be initialized after fetching data from an API.
Reveal solutionHide solution
1late String userData; // Use late because it will be set after async operation