Values and references

suggest change

In Dart every value is an object, including numbers, booleans, functions and null. A variable doesn't contain an object. It holds a reference to an object that lives on the heap. Assigning a variable, passing an argument and storing an element in a list all copy the reference, never the object.

That one rule explains a lot of behavior that surprises newcomers: why changing a list inside a function changes the caller's list, why List.filled(3, []) gives you three copies of the same list, and why a final field can still change.

This article covers:

The examples were run with Dart 3.13.

Assignment copies the reference

When you assign one variable to another, both variables refer to the same object. Changing the object through one variable is visible through the other:

class Point {
  int x;
  int y;
  Point(this.x, this.y);

  @override
  String toString() => 'Point($x, $y)';
}

void main() {
  var a = Point(1, 2);
  var b = a; // copies the reference, not the object

  b.x = 100;
  print(a);
  print(b);
  print(identical(a, b));

  b = Point(5, 5); // b now points at a new object; a is unaffected
  print(a);
  print(b);
  print(identical(a, b));
}

Output:

Point(100, 2)
Point(100, 2)
true
Point(100, 2)
Point(5, 5)
false

Keep these two operations apart:

Two variables that refer to the same object are called aliases. identical(a, b) tells you whether they are.

Immutable objects behave like values

Numbers, booleans and strings follow the same rule, but they look like they are copied. That's because they are immutable: no operation can change an int or a String. Operations like ++ or += create a new object and rebind the variable:

void main() {
  var n = 10;
  var m = n;
  m++; // m now refers to the int 11; n still refers to 10
  print('n=$n m=$m');

  var s = 'abc';
  var t = s;
  t += 'def'; // creates a new String and rebinds t
  print('s=$s t=$t');

  var list = [1, 2, 3];
  var alias = list;
  alias.add(4); // mutates the one shared list
  print('list=$list alias=$alias');
}

Output:

n=10 m=11
s=abc t=abcdef
list=[1, 2, 3, 4] alias=[1, 2, 3, 4]

m++ is shorthand for m = m + 1. It reassigns m. alias.add(4) mutates the list, so both variables see the change.

If nobody can mutate an object, sharing it can't cause surprises. In practice int, double, bool, String, Duration, DateTime, Uri, enums, records of immutable values and const objects all behave like values. Lists, sets, maps, StringBuffer and most classes you write are mutable, so sharing them matters. See Immutability for how to make your own classes immutable.

Passing arguments

Dart passes arguments by value, and the value being passed is a reference. The parameter is a new local variable that refers to the same object as the argument. So a function can mutate the caller's object, but it can't make the caller's variable refer to something else:

void addItem(List<String> items) {
  items.add('added'); // mutates the caller's list
}

void replaceList(List<String> items) {
  items = ['replaced']; // only rebinds the local parameter
  print('inside: $items');
}

void increment(int n) {
  n++; // the caller's variable is not affected
}

void swap(int a, int b) {
  final tmp = a;
  a = b;
  b = tmp;
}

void main() {
  final names = ['Ann'];
  addItem(names);
  print(names);

  replaceList(names);
  print(names);

  var count = 1;
  increment(count);
  print(count);

  var x = 1, y = 2;
  swap(x, y);
  print('x=$x y=$y');

  // Swapping is done in place, with a record pattern:
  (x, y) = (y, x);
  print('x=$x y=$y');
}

Output:

[Ann, added]
inside: [replaced]
[Ann, added]
1
x=1 y=2
x=2 y=1

Dart has no ref, out or & parameters like C#, C++ or Go pointers. increment and swap can't change the caller's variables. To swap two variables, use a pattern assignment like (x, y) = (y, x) (see Destructuring).

The analyzer lint parameter_assignments flags assignments to parameters like the one in replaceList. They are legal, but they often mean the author expected the caller to see the change.

Returning several values, and mutable boxes

Instead of output parameters, return a record. When a function really does need to update a value owned by the caller, pass a small mutable object:

// Return several values with a record instead of "out" parameters.
(int min, int max) minMax(List<int> values) {
  var lo = values.first, hi = values.first;
  for (final v in values) {
    if (v < lo) lo = v;
    if (v > hi) hi = v;
  }
  return (lo, hi);
}

// When a callee really must update the caller's value, pass a mutable box.
class Box<T> {
  T value;
  Box(this.value);
}

bool tryParseInt(String s, Box<int> out) {
  final n = int.tryParse(s);
  if (n == null) return false;
  out.value = n;
  return true;
}

void main() {
  final (lo, hi) = minMax([4, -2, 9, 3]);
  print('lo=$lo hi=$hi');

  final result = Box(0);
  if (tryParseInt('42', result)) {
    print('parsed ${result.value}');
  }
  print(tryParseInt('nope', result));
  print(result.value);
}

Output:

lo=-2 hi=9
parsed 42
false
42

The record version is the idiomatic one. Box is useful when several callbacks need to share and update one value. The function only receives a reference to the box, but it can change what the box holds. Here int.tryParse returning int? would be simpler still. Use a box only when a nullable return or a record doesn't fit.

Identity and equality

There are two ways to compare objects:

For booleans, null and numbers, the same value is always the same object, even when it comes from different computations. Strings are equal when they have the same characters, but two equal strings may be separate objects:

void main() {
  // Numbers: the same value is always the same object.
  final a = 1000000;
  final b = int.parse('1000000');
  print(identical(a, b));

  final big = 1 << 62;
  final big2 = int.parse('4611686018427387904');
  print(identical(big, big2));

  final d1 = 0.1 + 0.2;
  final d2 = 0.30000000000000004;
  print(identical(d1, d2));

  // Booleans and null are singletons.
  print(identical(1 < 2, true));

  // Strings: equal, but not necessarily the same object.
  final s1 = 'hello world';
  final s2 = 'hello world'; // same literal: canonicalized
  final s3 = ['hello', 'world'].join(' '); // built at run time
  print(s1 == s3);
  print(identical(s1, s2));
  print(identical(s1, s3));
}

Output (Dart VM and native executables):

true
true
true
true
true
true
false

So you never need to worry about whether two int objects are "the same int". (One exception: 0.0 == -0.0 is true, but they are different values and not identical.) For strings, always compare with ==. identical on strings depends on how they were created. When the same code is compiled to JavaScript, the last line prints true, because JavaScript strings compare by content.

Lists, sets and maps don't override ==, so two lists with the same elements are not equal. Classes you write compare by identity until you override == and hashCode. Both topics are covered in Equality and comparison.

const objects are canonicalized

The compiler creates exactly one object for each distinct constant value. Every const expression with the same value refers to that one object:

class Color {
  final int r, g, b;
  const Color(this.r, this.g, this.b);
}

void main() {
  // Every const expression with the same value is one canonical object.
  const l1 = [1, 2, 3];
  const l2 = [1, 2, 3];
  final l3 = [1, 2, 3];
  print(identical(l1, l2));
  print(identical(l1, l3));
  print(l1 == l3); // List == is identity

  const red1 = Color(255, 0, 0);
  const red2 = Color(255, 0, 0);
  final red3 = Color(255, 0, 0); // no const: a new object
  print(identical(red1, red2));
  print(identical(red1, red3));
}

Output:

true
false
false
true
false

Sharing a const object everywhere is safe because it is deeply immutable. Calling a const constructor without const (red3) creates a new object every time. This is why Flutter code puts const in front of widgets that never change. See Constants for more.

Records: values that hold references

Records are immutable and compare by value. Their fields are still references, though. A record that contains a list holds a reference to that list, and anyone who has the list can change it:

void main() {
  final p1 = (x: 1, y: 2);
  final p2 = (x: 1, y: 2);
  print(p1 == p2); // records compare by value
  print(p1.hashCode == p2.hashCode);

  // A record is immutable, but it holds references.
  final tags = ['a'];
  final r1 = (id: 1, tags: tags);
  final r2 = (id: 1, tags: ['a']);
  print(r1 == r2); // the lists are different objects

  tags.add('b'); // visible through the record
  print(r1);
}

Output:

true
true
false
(id: 1, tags: [a, b])

Record equality compares each field with ==. Two different lists are not ==, so r1 != r2 even though they print the same. A record only behaves fully like a value when all of its fields are immutable values.

Collections hold references

A list doesn't contain objects. It contains references to them. This matters when you fill a list with one object:

void main() {
  // List.filled puts the SAME object in every slot.
  final grid = List.filled(3, <int>[]);
  grid[0].add(1);
  print(grid);
  print(identical(grid[0], grid[2]));

  // List.generate calls the function for each slot: separate lists.
  final grid2 = List.generate(3, (_) => <int>[]);
  grid2[0].add(1);
  print(grid2);

  // Immutable values are fine with List.filled.
  final zeros = List.filled(3, 0);
  zeros[0] = 7;
  print(zeros);
}

Output:

[[1], [1], [1]]
true
[[1], [], []]
[7, 0, 0]

List.filled(3, <int>[]) evaluates <int>[] once and stores the same reference three times. Use List.generate when each element must be a separate mutable object. zeros[0] = 7 is fine because it replaces the reference in slot 0. It doesn't mutate the shared 0.

Shallow and deep copies

Copying a collection with List.of, toList(), [...list], Map.of or {...map} creates a new outer collection with the same element references. That's a shallow copy:

void main() {
  final matrix = [
    [1, 2],
    [3, 4],
  ];

  // toList(), [...spread] and List.of copy the outer list only.
  final shallow = [...matrix];
  shallow.add([5, 6]); // affects only the copy
  shallow[0][0] = 99; // affects the shared inner list
  print('matrix:  $matrix');
  print('shallow: $shallow');

  // A deep copy copies every level.
  final deep = [for (final row in matrix) [...row]];
  deep[0][0] = -1;
  print('matrix:  $matrix');
  print('deep:    $deep');
}

Output:

matrix:  [[99, 2], [3, 4]]
shallow: [[99, 2], [3, 4], [5, 6]]
matrix:  [[99, 2], [3, 4]]
deep:    [[-1, 2], [3, 4]]

Adding to shallow doesn't change matrix, but shallow[0] and matrix[0] are the same inner list. A deep copy copies every level until it reaches immutable values. Dart has no built-in deep copy. Write one for your data, as in the deep example, or use the techniques in Copying and cloning.

Mutable objects as map keys and set elements

Hash-based collections, including the default {} set and map, put each element in a bucket based on its hashCode when it's inserted. If you mutate a stored key in a way that changes its hashCode or ==, the collection can't find it any more:

class Key {
  String name;
  Key(this.name);

  @override
  bool operator ==(Object other) => other is Key && other.name == name;

  @override
  int get hashCode => name.hashCode;

  @override
  String toString() => 'Key($name)';
}

void main() {
  final k = Key('a');
  final set = {k};
  final map = {k: 1};

  k.name = 'b'; // mutate a key that is already stored

  print(set);
  print(set.contains(k));
  print(set.contains(Key('a')));
  print(map[k]);
  print(set.length);
  print(set.any((e) => identical(e, k)));
}

Output:

{Key(b)}
false
false
null
1
true

The set still holds the object (any finds it by scanning), but lookups by hash fail for both the old and the new name. Use immutable keys: strings, numbers, enums, records of immutable values, or classes with only final fields. If a key must change, remove it, change it and add it again.

Leaking references from classes

A final field can't be reassigned, but the object it refers to can still be mutated. When a constructor stores a list passed by the caller, or a getter returns an internal list, the caller and the object share it:

import 'dart:collection';

class LeakyTeam {
  final List<String> members;
  LeakyTeam(this.members); // stores the caller's list
}

class Team {
  final List<String> _members;
  Team(List<String> members) : _members = List.of(members); // copy in

  // Read-only view out: callers can't change our state.
  List<String> get members => UnmodifiableListView(_members);

  void add(String name) => _members.add(name);
}

void main() {
  final names = ['Ann', 'Bob'];

  final leaky = LeakyTeam(names);
  names.add('Mallory'); // the caller changes the team's state
  leaky.members.clear(); // and so can anyone with the getter
  print('leaky: ${leaky.members}, names: $names');

  final names2 = ['Ann', 'Bob'];
  final team = Team(names2);
  names2.add('Mallory');
  print('team: ${team.members}');
  try {
    team.members.add('Eve');
  } on UnsupportedError catch (e) {
    print('error: ${e.message}');
  }
  team.add('Carl');
  print('team: ${team.members}');
}

Output:

leaky: [], names: []
team: [Ann, Bob]
error: Cannot add to an unmodifiable list
team: [Ann, Bob, Carl]

LeakyTeam and the names variable share one list, so clear() through the team empties the caller's list too. Team makes a defensive copy on the way in and returns an UnmodifiableListView on the way out. The view doesn't copy anything. It wraps the internal list and throws on modification, but it still shows later changes made through add. Return List.unmodifiable(_members) instead if callers need a snapshot that won't change.

Default parameter values are constants

In some languages, a default value like def f(items=[]) in Python is created once and shared by every call, so it grows between calls. Dart avoids this: default values must be compile-time constants, and const collections can't be modified:

// Default values must be constants, so a default can't be a shared
// mutable list that grows between calls.
List<String> addTag(String tag, [List<String> tags = const []]) {
  return [...tags, tag];
}

List<String> addTagInPlace(String tag, [List<String>? tags]) {
  tags ??= []; // a fresh list on every call
  tags.add(tag);
  return tags;
}

void main() {
  print(addTag('a'));
  print(addTag('b'));
  print(addTagInPlace('a'));
  print(addTagInPlace('b'));

  try {
    // Mutating the const default fails at run time.
    final List<String> t = const [];
    t.add('x');
  } on UnsupportedError catch (e) {
    print('error: ${e.message}');
  }
}

Output:

[a]
[b]
[a]
[b]
error: Cannot add to an unmodifiable list

If a function needs a mutable default, make the parameter nullable and create the object in the body with ??=.

Closures capture variables

A closure doesn't copy the values of the variables it uses. It captures the variables themselves, so it sees later assignments and its own assignments are visible outside:

void main() {
  var counter = 0;
  void inc() => counter++; // captures the variable, not its value

  inc();
  inc();
  print(counter);

  counter = 100;
  inc();
  print(counter);

  // To capture the current value, copy it into a new variable.
  final callbacks = <void Function()>[];
  var i = 0;
  while (i < 3) {
    final snapshot = i;
    callbacks.add(() => print('i=$i snapshot=$snapshot'));
    i++;
  }
  for (final cb in callbacks) {
    cb();
  }
}

Output:

2
101
i=3 snapshot=0
i=3 snapshot=1
i=3 snapshot=2

All three closures share the one i declared outside the loop, so they print its final value. snapshot is a new variable on each iteration, so each closure gets its own. A for (var i = 0; ...) loop creates a fresh i per iteration automatically. See Lambdas and closures for more.

Isolates copy, they don't share

Isolates have separate heaps, so references can't cross between them. When you send a mutable object to another isolate, Dart copies the whole object graph:

import 'dart:isolate';

void main() async {
  final data = [1, 2, 3];

  // The list is copied into the new isolate; changes there stay there.
  final seen = await Isolate.run(() {
    data.add(4);
    return data;
  });
  print('in isolate: $seen');
  print('in main:    $data');

  // The returned list is a copy too.
  seen.add(5);
  print('in main:    $data');
}

Output:

in isolate: [1, 2, 3, 4]
in main:    [1, 2, 3]
in main:    [1, 2, 3]

The closure passed to Isolate.run captures data, and the captured list is copied along with the closure. The result is copied back the same way. Deeply immutable objects such as strings, numbers and const values can be shared without copying. For large binary data, use TransferableTypedData to move a buffer without copying it.

The cost of copying

Passing a reference costs the same no matter how big the object is. Copying costs time and memory proportional to its size. This program sums a million-element list 100 times, once by passing the list directly and once by copying it first:

int sumShared(List<int> values) {
  var total = 0;
  for (final v in values) {
    total += v;
  }
  return total;
}

int sumCopy(List<int> values) => sumShared(List.of(values));

void main() {
  final values = List.generate(1000000, (i) => i);
  const rounds = 100;

  // Warm up both functions so the JIT compiles them.
  for (var i = 0; i < 10; i++) {
    sumShared(values);
    sumCopy(values);
  }

  var sw = Stopwatch()..start();
  var check = 0;
  for (var i = 0; i < rounds; i++) {
    check += sumShared(values);
  }
  print('pass reference: ${sw.elapsedMilliseconds} ms');

  sw = Stopwatch()..start();
  for (var i = 0; i < rounds; i++) {
    check -= sumCopy(values);
  }
  print('copy first:     ${sw.elapsedMilliseconds} ms');
  print(check);
}

Output from one run with dart run (the numbers vary between runs and machines):

pass reference: 257 ms
copy first:     724 ms
0

Copying made each call about three times slower here, and each copy allocated another million-element list for the garbage collector to clean up. Make defensive copies where they protect an invariant, at the boundary of a class or library. Don't copy on every call inside code you control. When data is immutable, you can share it freely and don't need to copy at all.

Making a class behave like a value

To get value semantics for your own types, combine the two techniques: make the class immutable and give it value equality. Operations then return new objects instead of changing existing ones:

// An immutable class with value equality behaves like a value:
// sharing it is safe and == compares contents.
final class Money {
  final int cents;
  final String currency;
  const Money(this.cents, this.currency);

  Money operator +(Money other) {
    if (other.currency != currency) throw ArgumentError('currency mismatch');
    return Money(cents + other.cents, currency); // a new object
  }

  @override
  bool operator ==(Object other) =>
      other is Money && other.cents == cents && other.currency == currency;

  @override
  int get hashCode => Object.hash(cents, currency);

  @override
  String toString() => '${(cents / 100).toStringAsFixed(2)} $currency';
}

void main() {
  final price = Money(1999, 'USD');
  final alias = price;
  final total = alias + Money(500, 'USD'); // price is untouched

  print('price=$price total=$total');
  print(price == Money(1999, 'USD'));
  print(identical(price, Money(1999, 'USD')));
  print({price, Money(1999, 'USD')}.length);
}

Output:

price=19.99 USD total=24.99 USD
true
false
1

Money objects are still passed by reference, but since nobody can change them, the program can't tell the difference. final class stops other libraries from creating mutable subclasses. For simple cases, a record such as (cents: 1999, currency: 'USD') gives you the same behavior with no code.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents