首页 > 解决方案 > How to return an immutable List in Dart?

问题描述

So in other languages there are ArrayList or MutableList which allows modifications (add, delete, remove) to list items. Now to avoid modification of these list, simply return the MutableList or ArrayList as a List.

I want to do the same thing in Dart. But in Dart returning a List still allows you to do list.add. How can this be done properly in Dart?

标签: dart

解决方案


You may use Iterable<type>. It is not a List<type>, it does not provide methods to modify, but it does to iterate. It also provides a .toList() method, if needed. Depending on your construction, it may be better to use Iterable instead of List to ensure consistency.

Almost good

final Iterable<int> foo = [1, 2, 3];
foo.add(4); // ERROR: The method 'add' isn't defined.

// Warning: following code can be used to mutate the container.
(foo as List<int>).add(4);
print(foo); // [1, 2, 3, 4]

Even though foo is instantiated as a mutable List, the interface only says it is a Iterable.

Good

final Iterable<int> foo = List.unmodifiable([1, 2, 3]);
foo.add(4); // ERROR: The method 'add' isn't defined.

(foo as List<int>).add(4); // Uncaught Error: Unsupported operation: add

// The following code works but it is 
// OK because it does not mutate foo as 
// foo.toList() returns a separate instance.
foo.toList().add(4);
print(foo); // [1, 2, 3]

推荐阅读