{

Dart| Flutter: Multiple ways to create immutable List with examples


This tutorial shows multiple ways to create an immutable list.

The list is a mutable list in a dart that allows adding, removing, and updating operations.

Immutable lists do not allow to add 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example