{

Dart| Flutter: Multiple ways to create immutable List with 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 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: Find a Given String is numeric or not

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example