Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an immutable List in Dart?

Tags:

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?

like image 559
Archie G. Quiñones Avatar asked Oct 07 '19 15:10

Archie G. Quiñones


2 Answers

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.
final a = foo.toList();
a.add(4);
print(a); // [1, 2, 3, 4]
like image 83
rserro Avatar answered Oct 20 '22 13:10

rserro


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.

Compile time constant list variables

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];

Compile time constant list values

If the variable can't be a const, you can still make the value be const.

final myList = const [1, 2, 3];

Runtime constant list

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]);
like image 27
Suragch Avatar answered Oct 20 '22 14:10

Suragch