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?
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.
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
.
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.
final a = foo.toList();
a.add(4);
print(a); // [1, 2, 3, 4]
As Irn said, there is no type for immutable lists in Dart, but this supplemental answer shows examples of creating immutable lists. You can't add, remove, or modify the list elements.
Use the const
keyword to create the list.
const myList = [1, 2, 3];
Note: Adding the optional const
keyword before the list literal is redundant when the variable is already const
.
const myList = const [1, 2, 3];
If the variable can't be a const
, you can still make the value be const
.
final myList = const [1, 2, 3];
If you don't know what the list elements are until runtime, then you can use the List.unmodifiable()
constructor to create an immutable list.
final myList = List.unmodifiable([someElement, anotherElement]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With