Mutable, Immutable, and Unmodifiable Lists in Flutter

 

In this blog, we will explore the key concepts of mutable, immutable, and unmodifiable lists in Flutter. We’ll explain how these types of lists differ, their use cases, and how to implement them using Dart code. By the end of this post, you’ll gain a solid understanding of managing data with these list types in Flutter. The concepts will be demonstrated through a practical code example that highlights the behavior of a mutable list and an unmodifiable list in a simple Flutter app.

Intro:

When working with lists in Flutter, understanding the differences between mutable, immutable, and unmodifiable lists is crucial. These terms determine how lists can be modified during runtime, affecting the flexibility and stability of your Flutter app.

In this article, we will break down these three types of lists with an example to demonstrate their behaviors. Let’s dive into their definitions first, and then move on to a practical example to understand them better.

What is a Mutable List?

A mutable list is a list that can be changed after its creation. This means you can add, remove, or update elements in the list at any time. By default, lists in Dart (Flutter) are mutable.

For example:

List<String> mutableList = ["Apple", "Banana", "Cherry"];
mutableList.add("Dragonfruit"); // The list is now ["Apple", "Banana", "Cherry", "Dragonfruit"]

 

What is an Immutable List?

An immutable list, on the other hand, cannot be modified once it’s created. Dart does not provide immutable lists directly, but you can ensure immutability by not exposing the list’s reference or using libraries that support immutability.

What is an Unmodifiable List?

An unmodifiable list is a special type of list in Dart. Once created, it cannot be changed. Unlike immutable lists, Dart provides built-in support for unmodifiable lists using the List.unmodifiable() constructor.

For example:

List<String> unmodifiableList = List.unmodifiable(mutableList);
unmodifiableList.add("Elderberry"); // This will throw an exception

 

Flutter Example: Demonstrating Mutable vs Unmodifiable Lists

Let’s see how mutable and unmodifiable lists work in a Flutter app. We’ll create a simple app with buttons to try adding or removing elements from an unmodifiable list.

Here’s the code:

import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

List<String> list = ["Abc","Def","Ghi","Jkl"];
List<String> unModifiable = List.unmodifiable(list);

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("ListView Example"),
        ),
        body: Center(
          child: Column(
            children: [
              TextButton(
                onPressed: (){
                  setState(() {
                    unModifiable.add("comp");  // This will cause an error
                  });
                },
                child: const Text("Add Element to List"),
              ),
              TextButton(
                onPressed: (){
                  setState(() {
                    unModifiable.removeAt(2);  // This will also cause an error
                  });
                },
                child: const Text("Remove Element from List"),
              ),
              TextButton(
                onPressed: (){
                  print(unModifiable);  // Will print the unmodifiable list
                },
                child: const Text("Display List"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

 

1. Mutable List:

•We define a List<String> list = [“Abc”, “Def”, “Ghi”, “Jkl”];. This list is mutable, meaning we can add, remove, or modify its elements freely.

2. Unmodifiable List:

•We then create unModifiable = List.unmodifiable(list);. This list cannot be altered after it has been created. Attempts to modify this list will result in a runtime error.

 

Why Use Unmodifiable Lists?

Unmodifiable lists can be particularly useful in scenarios where you want to ensure that no part of your code (or external users) can alter the data structure after its creation. This helps in maintaining the integrity of the data and can prevent unwanted bugs in your application.

Conclusion:

In this blog, we explored the differences between mutable, immutable, and unmodifiable lists in Flutter. By understanding how these lists function, you can manage your data effectively and choose the right type of list depending on your app’s needs.

Using the provided Flutter example, we demonstrated that attempting to modify an unmodifiable list will result in a runtime error, ensuring that the list remains unchanged.

Feel free to try this code in your Flutter project and see how these list types behave!

 

Also below i am providing a example of how to play with a simple list useful for beginners to get quick understanding

import 'package:flutter/material.dart';

void main(){
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<String> list = const ["Abc","Def","Ghi","Jkl"];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Live Template"),
        ),
        body: Center(
          child: Column(
            children: [
              TextButton(
                onPressed: (){
                  setState(() {
                    list.add("comp");
                  });
                },
                child: const Text("Add Element to List"),
              ),TextButton(
                onPressed: (){
                  setState(() {
                    list.removeAt(2);
                  });
                },
                child: const Text("Remove Element from List"),
              ),
              TextButton(
                onPressed: (){
                  print(list);
                },
                child: const Text("Display List"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

 

Show Buttons
Hide Buttons
Read previous post:
Flutter Network Status Checker
Flutter Network Status Checker | Best Way to Check Internet

Flutter Network Status Checker : In this blog, we’ll explore how to create a Flutter Network Status Checker. This simple...

Close