Multiple ways to create immutable List in dart examples
This tutorial shows multiple ways to create an immutable list in dart and flutter
The list is a mutable list in a dart that allows adding, removing, and updating operations.
Immutable lists do not allow adding or update operations and allow only read operations. Due to reading operations, Immutable List is best in performance compared with List.
Sometimes, We want to return APIs or methods to return immutable List only.
For example, Normal List allows adding, updating, and removing operations as given below.
void main() {
var list = [8, 6, 3];
print(list); //[8, 6, 3];
list.add(2);
print(list); //[8, 6, 3, 2]
list.remove(6);
print(list); //[8, 3, 2]
}
There are multiple ways we can create an immutable list.
Dart or Flutter Create an immutable List
- use List.unmodifiable method
List.unmodifiable()
method takes list argument and returns immutable list.
Here is an example
void main() {
var list = [8, 6, 3];
print(list); //[8, 6, 3];
var unmodifiable = List<int>.unmodifiable(list);
print(unmodifiable); //[8, 6, 3, 2]
}
Suppose, It throws an error Uncaught Error: Unsupported operation: remove
if you try to add or remove an element from the unmodifiable list.
The below code throws an error
void main() {
var list = [8, 6, 3];
print(list); //[8, 6, 3];
var unmodifiable = List<int>.unmodifiable(list);
unmodifiable.add(5); // error
unmodifiable.remove(6); // error
}
- Use constantly for variable declaration.
Another way to declare a list with either final or const.
Instead of var keyword, use const or final
to create a list and assign the values on the same line.
You can declare compile-time constant variables
const list = [8, 6, 3];
Similarly, you can use
const list = const [8, 6, 3];
Here is an example of an immutable list.
void main() {
const list = [8, 6, 3];
print(list); //[8, 6, 3];
list.add(5); // error
list.remove(6); // error
}
Conclusion
Learned multiple ways to create an immutable or unmodifiable list in dart or flutter with examples.