DartIntermediate 2 min read

Dart generic variance: avoid unsafe collection mutation

Explain why a wider static view does not change the concrete element contract of a list.

On this page

Generic relationships can look safe until a mutation reaches a collection with a narrower element contract. Dart combines static analysis with runtime checks to preserve soundness. Prefer an API that accepts only the operations it needs.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
void main() {
  final integers = <int>[1, 2];
  List<num> widerView = integers;
  try {
    widerView.add(2.5);
  } on TypeError {
    print('Rejected a double in the original int list.');
  }
  final independent = <num>[...integers, 2.5];
  print(independent.length);
}

Follow the data and control flow

The view’s static type permits a number, but the underlying list still has an int element contract. The runtime rejects inserting a double. A separate list with a num element type can contain both integers and doubles.

If a function only reads a sequence, accepting Iterable<num> can avoid advertising mutation through that parameter. Generic function and method variance also matters for substitutability: a callback accepting a narrower type is not automatically usable where every broader input must be handled.

A mistake to avoid

Using dynamic or an unchecked cast does not make a narrower collection safely mutable with every value. Do not treat the caught TypeError as ordinary validation for external data; design the API so the incompatible mutation is not attempted.

Practice and verification

Replace the view with an independent List<num>.of copy and verify both lists after insertion. Write a read-only sum function and explain why it does not need access to add. Connect that contract to a public generic repository API.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.