Dart/Flutter: How to create an immutable list?

If you come from another programming language like Scala where you can easily create immutable lists — and many other immutable things — working with Dart (and Flutter) can be a major change, possibly because Dart was designed to be a pure OO language.

That being said, I just saw that there is a way to create an immutable list in Dart:

// create an immutable list
final List<int> xs = List.unmodifiable([1,2,3]); // [1, 2, 3]

// these two exceptions demonstrate that the list is immutable
xs.add(4);     // Throws "Unsupported operation: indexed setError"
xs[0] = 100;   // Throws "Unsupported operation: indexed setError"

You can copy and paste that code into DartPad to demonstrate that for yourself.

For more details on immutable Dart lists, see the List.unmodifiable constructor page, which states, “Creates an unmodifiable list containing all elements.” The page also notes that the unmodifiable constructor takes an Iterable as its parameter; this is why I pass an existing List<Int> into it in my example.

Tip: It’s also important to know that if you’re putting mutable objects in an immutable list, you’re not getting the “safety” benefits you may be hoping for. (That’s because the mutable objects can still be modified, even while they’re in the immutable list.)

In a related note, I see that there is a Fast immutable collections project. Their benchmarks show that in addition to being immutable collections, they also appear to be much faster than the default collections (possibly because they don’t have to worry about the concerns of being mutable).