Immutability
suggest changeAn immutable value can't change after it has been created. Immutable data is easier to reason about: you can share it between functions, store it in a cache or a Set, and send it across Isolates without worrying that someone else modifies it behind your back.
Dart doesn't have a single "immutable" switch. Instead, it gives you several tools that work at different levels:
finalandconstvariables, which can't be reassigned.finalfields andconstconstructors, which make objects immutable.- Unmodifiable collections (
List.unmodifiable,UnmodifiableListView,constliterals). - Records and enums, which are immutable by design.
- The
@immutableannotation andfinal classmodifier, which let the analyzer and compiler help enforce the rules.
The difference between final and const variables is covered in Constants. This article focuses on making data, not just variables, immutable.
A fixed variable is not an immutable value
final only means the variable can't be pointed at a different object. The object itself can still be mutated:
void main() {
final names = ['Ann', 'Bob'];
// names = ['Carl']; // compile error: The final variable 'names' can only be set once
names.add('Carl'); // allowed: the list object itself is mutable
names[0] = 'Anna';
print(names);
}
Output:
[Anna, Bob, Carl]
To get a value that really can't change, the object itself must refuse modification. For built-in types that's already true: int, double, bool, String, Duration and DateTime are all immutable. Methods that look like they modify them return a new object instead:
void main() {
final s = 'hello';
final upper = s.toUpperCase();
print('$s $upper');
final start = DateTime.utc(2026, 1, 31);
final later = start.add(const Duration(days: 1));
print(start);
print(later);
}
Output:
hello HELLO
2026-01-31 00:00:00.000Z
2026-02-01 00:00:00.000Z
late final: assign exactly once
Sometimes a value can't be computed when the object is created, but should never change once it is set. A late final variable can be assigned once at runtime. A second assignment throws:
class Connection {
late final String sessionId;
void open() {
sessionId = 'sess-42';
}
}
void main() {
final c = Connection();
c.open();
print(c.sessionId);
try {
c.open(); // second assignment
} on Error catch (e) {
print(e);
}
}
Output:
sess-42
LateInitializationError: Field 'sessionId' has already been initialized.
Reading a late final variable before it was assigned also throws, so use it only when you are sure about the initialization order.
Unmodifiable collections
Dart collections are mutable by default. There are several ways to get one that rejects changes, and they behave differently.
To show which operations fail, the examples below use a small helper:
void attempt(String label, void Function() action) {
try {
action();
print('$label: ok');
} on UnsupportedError {
print('$label: UnsupportedError');
}
}
const literals
A const list, set or map is fixed at compile time. Every element must also be a constant, so the whole structure is deeply immutable:
void main() {
const primes = [2, 3, 5, 7];
const config = {'host': 'localhost', 'port': 8080};
attempt('add to const list', () => primes.add(11));
attempt('set const list element', () => primes[0] = 1);
attempt('put in const map', () => config['host'] = 'example.com');
print(primes);
}
Output:
add to const list: UnsupportedError
set const list element: UnsupportedError
put in const map: UnsupportedError
[2, 3, 5, 7]
Note that the errors happen at runtime. The static type of primes is still List<int>, which has an add method, so the code compiles.
List.unmodifiable, Set.unmodifiable, Map.unmodifiable
When the contents are only known at runtime, use the unmodifiable constructors. They copy the source into a new collection that can't be changed:
void main() {
final source = ['red', 'green'];
final colors = List.unmodifiable(source);
attempt('add', () => colors.add('blue'));
attempt('remove', () => colors.remove('red'));
attempt('sort', () => colors.sort());
source.add('blue'); // changing the source doesn't affect the copy
print(source);
print(colors);
final tags = Set.unmodifiable({'dart', 'flutter'});
final ages = Map.unmodifiable({'Ann': 31, 'Bob': 27});
attempt('add to set', () => tags.add('go'));
attempt('remove from map', () => ages.remove('Ann'));
}
Output:
add: UnsupportedError
remove: UnsupportedError
sort: UnsupportedError
[red, green, blue]
[red, green]
add to set: UnsupportedError
remove from map: UnsupportedError
UnmodifiableListView and friends
dart:collection has UnmodifiableListView, UnmodifiableSetView and UnmodifiableMapView. They don't copy anything. They wrap an existing collection and forward reads to it, while rejecting writes. Changes made to the underlying collection are visible through the view:
import 'dart:collection';
void main() {
final items = [1, 2, 3];
final view = UnmodifiableListView(items);
attempt('add through view', () => view.add(4));
items.add(4); // the owner can still change it
print(view);
}
Output:
add through view: UnsupportedError
[1, 2, 3, 4]
This makes views ideal for a class that owns a mutable collection and wants to expose it read-only, without copying on every access:
import 'dart:collection';
class ShoppingCart {
final List<String> _items = [];
UnmodifiableListView<String> get items => UnmodifiableListView(_items);
void add(String item) => _items.add(item);
}
void main() {
final cart = ShoppingCart();
cart.add('milk');
cart.add('bread');
print(cart.items);
attempt('modify from outside', () => cart.items.clear());
}
Output:
[milk, bread]
modify from outside: UnsupportedError
Returning Iterable<String> instead of List<String> is not real protection: a caller can write (cart.items as List<String>).clear() and mutate your internal list.
Fixed-length lists
toList(growable: false) and List.filled create fixed-length lists. Their length can't change, but elements can still be replaced. They are not immutable:
void main() {
final fixed = [1, 2, 3].toList(growable: false);
attempt('add', () => fixed.add(4));
attempt('set element', () => fixed[0] = 100);
print(fixed);
}
Output:
add: UnsupportedError
set element: ok
[100, 2, 3]
Summary
| Approach | Copies? | Sees later source changes? | Element replacement | Deep? |
|---|---|---|---|---|
const [...] |
n/a | n/a | no | yes |
List.unmodifiable(src) |
yes | no | no | no |
UnmodifiableListView(src) |
no | yes | no | no |
toList(growable: false) |
yes | no | yes | no |
"Deep" means the elements are also immutable. An unmodifiable list of mutable objects still lets you mutate those objects.
Immutable classes
A class is immutable when all its fields are final and every field holds an immutable value. If every field can be computed at compile time, give the class a const constructor:
class Point {
final int x;
final int y;
const Point(this.x, this.y);
Point translate(int dx, int dy) => Point(x + dx, y + dy);
@override
String toString() => 'Point($x, $y)';
}
void main() {
const origin = Point(0, 0);
final moved = origin.translate(3, 4);
print(origin);
print(moved);
// origin.x = 10; // compile error: 'x' can't be used as a setter because it's final
const a = Point(1, 2);
const b = Point(1, 2);
print(identical(a, b)); // const instances are canonicalized
}
Output:
Point(0, 0)
Point(3, 4)
true
"Modifying" methods like translate return a new instance. For classes with many fields, the usual pattern is a copyWith method, described in Copying and cloning.
Defensive copies for collection fields
A final List<String> field is a trap: the field can't be reassigned, but the list can be changed by anyone who has a reference to it, including the code that passed it to the constructor:
class Team {
final String name;
final List<String> members;
Team(this.name, this.members);
}
void main() {
final people = ['Ann', 'Bob'];
final team = Team('core', people);
people.add('Mallory'); // caller still holds the list
team.members.clear(); // anyone can mutate the field
print(team.members);
}
Output:
[]
Fix it by copying the input into an unmodifiable list in the initializer list:
class Team {
final String name;
final List<String> members;
Team(this.name, List<String> members) : members = List.unmodifiable(members);
}
void main() {
final people = ['Ann', 'Bob'];
final team = Team('core', people);
people.add('Mallory');
print(team.members);
attempt('clear members', () => team.members.clear());
}
Output:
[Ann, Bob]
clear members: UnsupportedError
The trade-off is that List.unmodifiable runs at runtime, so this constructor can't be const. If you need both, provide a const constructor for constant data and a factory or named constructor that makes the defensive copy.
Value equality
By default, == compares identity. Two separately created immutable objects with the same fields are not equal unless you override == and hashCode. Since the fields never change, the hash code is stable, which makes immutable objects safe to use as Map keys and Set elements:
class Money {
final int cents;
final String currency;
const Money(this.cents, this.currency);
@override
bool operator ==(Object other) =>
other is Money && other.cents == cents && other.currency == currency;
@override
int get hashCode => Object.hash(cents, currency);
}
void main() {
final a = Money(500, 'USD');
final b = Money(500, 'USD');
print(a == b);
final prices = {a, b, Money(500, 'EUR')};
print(prices.length);
}
Output:
true
2
Never use mutable fields in hashCode: if a field changes after the object was added to a Set, the set can no longer find it. See Equality and comparison for the details.
The @immutable annotation
package:meta provides an @immutable annotation. It doesn't change runtime behavior, but the analyzer reports a warning when the class, or any subclass, has a field that is not final:
import 'package:meta/meta.dart';
@immutable
class User {
final String name;
int loginCount = 0; // warning: must_be_immutable
User(this.name);
}
class Admin extends User {
String role; // warning: must_be_immutable (inherited from User)
Admin(super.name, this.role);
}
Add the package with dart pub add meta. In Flutter, the annotation is re-exported by package:flutter/foundation.dart, which is why every Widget subclass must have only final fields.
@immutable checks only that fields are final. It does not detect a final List<String> field that is mutable inside, so the defensive copy technique above still matters.
Preventing mutable subclasses
Even if your class is immutable, someone can extend it and add mutable state, then pass the subclass wherever your type is expected. Since Dart 3, the final class modifier prevents classes in other libraries from extending or implementing yours:
final class Temperature {
final double celsius;
const Temperature(this.celsius);
double get fahrenheit => celsius * 9 / 5 + 32;
}
// In another library:
// class MutableTemperature extends Temperature { ... }
// error: The class 'Temperature' can't be extended outside of its library because it's a final class.
void main() {
const t = Temperature(21.5);
print(t.fahrenheit);
}
Output:
70.7
See Inheritance for all class modifiers.
Records are immutable
Records, added in Dart 3, are lightweight immutable values. Their fields have getters but no setters, and they have built-in structural equality:
(double, double) minMax(List<double> values) {
var min = values.first;
var max = values.first;
for (final v in values) {
if (v < min) min = v;
if (v > max) max = v;
}
return (min, max);
}
void main() {
final range = minMax([3.5, -1.0, 7.25]);
print(range);
print(range.$1);
// range.$1 = 0; // compile error: The setter '$1' isn't defined for the type '(double, double)'
final user = (name: 'Ann', age: 31);
print(user.name);
// "Change" a record by creating a new one
final older = (name: user.name, age: user.age + 1);
print(older.age);
print((1, 'a') == (1, 'a'));
print(([1, 2],) == ([1, 2],)); // fields compared with ==, lists by identity
}
Output:
(-1.0, 7.25)
-1.0
Ann
32
true
false
The last line shows that a record is only as immutable as its fields. A record holding a List is shallowly immutable, exactly like a class with a final List field. Records combine well with Destructuring and Pattern matching.
Enums are immutable
Every enum value is a compile-time constant. Fields of enhanced enums must be final and the constructor must be const:
enum Planet {
mercury(3.303e+23, 2.4397e6),
earth(5.976e+24, 6.37814e6);
final double mass;
final double radius;
const Planet(this.mass, this.radius);
double get surfaceGravity => 6.67300e-11 * mass / (radius * radius);
}
void main() {
for (final p in Planet.values) {
print('${p.name}: ${p.surfaceGravity.toStringAsFixed(2)} m/s^2');
}
}
Output:
mercury: 3.70 m/s^2
earth: 9.80 m/s^2
Code generation: freezed and built_value
Writing ==, hashCode, toString and copyWith by hand for every data class is tedious and error-prone. Two popular packages generate them for you.
With freezed:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
@freezed
abstract class Person with _$Person {
const factory Person({
required String name,
required int age,
@Default([]) List<String> nicknames,
}) = _Person;
}
After running dart run build_runner build, Person gets value equality, a readable toString, and a copyWith that can also set nullable fields to null. By default freezed also wraps collection fields like nicknames in unmodifiable views, so the generated class is deeply immutable when its element types are.
built_value takes a stricter approach, combining immutable classes with the built_collection package (BuiltList, BuiltMap) and a builder pattern for making modified copies.
Best practices
- Make fields
finalby default. Add mutability only when you need it. - Add a
constconstructor to classes whose fields are allfinaland constant-friendly, so callers can create canonical instances. - Don't trust
finalalone for collection fields. Copy inputs withList.unmodifiableor expose internal state throughUnmodifiableListView. - Override
==andhashCode(or use records or freezed) for immutable value types, and never base a hash code on mutable state. - Use
@immutableto let the analyzer catch non-final fields, andfinal classwhen subclasses must not add mutable state. - Prefer records for small, ad-hoc immutable groupings such as multiple return values; use a class when the value needs methods, validation or a name.