Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Flutter and app store releases

Dart throws Unsupported operation when code adds to a list

Your error

Unsupported operation: Cannot add to an unmodifiable list3 more lines it can show

Fix it fast

Most common cause, 1 of 3

The list is a const literal, often a const [] parameter default

Keep const [] as the default value, but copy it into a growable list in the initializer list.

Fix
class CartModel {
  CartModel({List<String> items = const []}) : items = List.of(items);
  final List<String> items;
}

// or leave the old list alone and make a new one:
final next = [...cart.items, 'apple'];
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

Unsupported operation: Cannot add to an unmodifiable list means add(), insert() or addAll() ran on a list that refuses changes: a const literal (often a const [] default value), a freezed model field, or the result of List.unmodifiable or UnmodifiableListView. Build a growable copy with List.of(items) or [...items, x] and change that. Applies to Dart 3.10 to 3.14.

  • Applies to Dart 3.10 to 3.14 (Flutter 3.38 to 3.50.x), freezed 4.0.3, Dart VM targets: Android, iOS, desktop
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

The top frame of your own code in the stack trace is the add() call. Then find where that list was born: search lib/ for the three things that create read-only lists, and match the hit to the variable on the failing line.

Run this first
grep -rnE "const \[|const <[A-Za-z]+>\[|List\.unmodifiable|UnmodifiableListView|@freezed|@Freezed" lib/

Then find the line you see in this list and open its fix:

  1. 1The list is a const literal, often a const [] parameter defaultThe variable traces back to const [...] or to a constructor default such as this.items = const []
  2. 2A freezed class turned its List field into an unmodifiable viewThe list is a property of a class annotated with @freezed, and printing its runtimeType shows a class name ending in UnmodifiableListView
  3. 3A class exposes its list through List.unmodifiable or UnmodifiableListViewThe list comes from a getter or a package method, and its source wraps the data in UnmodifiableListView or List.unmodifiable

What does the error look like?

  • Unsupported operation: Cannot add to an unmodifiable list
  • Unsupported operation: Cannot remove from an unmodifiable list
  • Unsupported operation: Cannot modify an unmodifiable list
  • Unsupported operation: Cannot clear an unmodifiable list

Cause 1 of 3

The list is a const literal, often a const [] parameter default

You seeThe variable traces back to const [...] or to a constructor default such as this.items = const []

Check

Cannot add to an unmodifiable list on a const list happens because a const list literal is a compile-time constant, and the Dart VM backs it with an immutable list class that rejects add, insert and addAll. A constructor that defaults a field to const [] gives that frozen list to every caller who skips the argument, so the first add() on the field throws.

Check
class CartModel {
  CartModel({this.items = const []});
  final List<String> items;
}

CartModel().items.add('apple'); // Unsupported operation

Fix

Keep const [] as the default value, but copy it into a growable list in the initializer list. List.of returns a growable list unless you pass growable: false. Code that never needs to mutate can instead build a new list with the spread operator.

Fix
class CartModel {
  CartModel({List<String> items = const []}) : items = List.of(items);
  final List<String> items;
}

// or leave the old list alone and make a new one:
final next = [...cart.items, 'apple'];

Verify

Adding to the field of a model built without arguments works and the length goes up by one.

Verify
final cart = CartModel();
cart.items.add('apple');
print(cart.items.length); // 1

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 2 of 3

A freezed class turned its List field into an unmodifiable view

You seeThe list is a property of a class annotated with @freezed, and printing its runtimeType shows a class name ending in UnmodifiableListView

Check

In a @freezed model, Cannot add to an unmodifiable list comes from the generated code. Freezed converts List, Map and Set properties into unmodifiable views by default (@unfreezed classes are exempt), so model.items.add(x) compiles because the type says List, then throws when it runs.

Check
debugPrint(cart.items.runtimeType.toString());

Fix

Treat the model as a value: create the longer list and hand it to copyWith, then store the returned object in your state. If the class truly has to be mutable, turn the conversion off with makeCollectionsUnmodifiable: false and run the generator again.

Fix
final updated = cart.copyWith(items: [...cart.items, 'apple']);

// opting out, only for a model that must stay mutable:
@Freezed(makeCollectionsUnmodifiable: false)
abstract class Cart with _$Cart {
  factory Cart(List<String> items) = _Cart;
}

dart run build_runner build

Verify

The screen shows the extra item after the new model is stored, and the old model still holds the old list.

Verify
print(cart.items.length);    // old length
print(updated.items.length); // old length + 1

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 3 of 3

A class exposes its list through List.unmodifiable or UnmodifiableListView

You seeThe list comes from a getter or a package method, and its source wraps the data in UnmodifiableListView or List.unmodifiable

Check

A read-only getter is deliberate: the owner returns UnmodifiableListView or List.unmodifiable so that changes go through its own methods. UnmodifiableListView extends UnmodifiableListBase, the same base whose add() raises Cannot add to an unmodifiable list, so calling add() on what the getter hands back fails by design.

Check
grep -rn "UnmodifiableListView\|List.unmodifiable" lib/

Fix

Add through the owner's method, which can also notify listeners. When you only need a private working list, copy the view with List.of and change the copy.

Fix
import 'dart:collection';
import 'package:flutter/foundation.dart';

class CartNotifier extends ChangeNotifier {
  final List<String> _items = [];
  UnmodifiableListView<String> get items => UnmodifiableListView(_items);

  void add(String item) {
    _items.add(item);
    notifyListeners();
  }
}

cart.add('apple');                        // instead of cart.items.add('apple')
final scratch = List.of(cart.items)..add('pear');

Verify

cart.items shows the new entry through the view, and widgets that listen to the notifier rebuild.

Verify
print(cart.items); // [apple]

Confirmed by raw.githubusercontent.com

Did this fix it?

How do I stop it coming back?

  • Type list fields that callers must not change as List but copy them with List.of in the constructor, so a const [] default can never leak into code that mutates.
  • In freezed models, update collections only through copyWith with a new list; keep makeCollectionsUnmodifiable at its default unless the class must be mutable.
  • Expose internal lists as UnmodifiableListView and give the class add and remove methods, so the read-only contract is visible in the type instead of failing at run time.
  • Add a unit test that builds each model with its default arguments and runs the methods that mutate its lists.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: TaxiDex, Qist Bazaar, SessionBird.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.