Back to results for “Dart Collections & Generics”
Flutter › Dart Collections & Generics

What are unmodifiable and immutable collections in Dart, and why might you deliberately choose to use one instead of a regular mutable collection in certain parts of your code?

Intermediate

Answer

An unmodifiable collection, created using a constructor such as List.unmodifiable, throws an error if any code ever attempts to modify it after its initial creation, such as adding or removing an item, and deliberately using unmodifiable collections in appropriate places, such as when exposing a private internal list publicly from a class, helps prevent unintended external modification of data that should genuinely remain fixed and protected, catching an accidental mutation mistake early with a clear error rather than allowing silent, unexpected changes to data elsewhere in a large codebase.
class ShoppingCart {
  final List<String> _items = [];
  List<String> get items => List.unmodifiable(_items);
}
Real-world example A ShoppingCart class exposes its internal items list only as an unmodifiable copy through its public getter, preventing external code from accidentally directly modifying the cart's actual internal contents without going through the class's own properly controlled methods.

Common follow-ups: What is the performance cost of creating an unmodifiable copy of a large collection?;How does Dart's const keyword relate to creating a fully immutable collection at compile time?