Dart Collections: Mutable List & Immutable Lists

Dart Collections: Mutable List & Immutable Lists

Dart Collections: Lists that Move and Lists that Stay

In the world of Dart collections, Lists are like dynamic party guests – they can either change their dance moves (Mutable Lists) or stay as they are, following a set routine (Immutable Lists).

1. Mutable Lists: Dance Floor Vibes

Mutable Lists are the life of the party. They can groove, shuffle, and switch partners whenever they feel like it. Adding, removing, or updating items – it's all fair game.

List<String> partyPlaylist = ['Pop', 'Rock', 'Hip-Hop'];
partyPlaylist.add('EDM'); // Adding a new genre
partyPlaylist.remove('Rock'); // Removing a genre
partyPlaylist[1] = 'Indie'; // Updating a genre

In this example, our party playlist is mutable. We add EDM, remove Rock, and update the second genre to Indie. The list is as flexible as a dance floor, adapting to the music vibe.

2. Immutable Lists: The Statue in the Garden

Immutable Lists are like statues in a serene garden – once placed, they stay put. You can't add, remove, or change them. They maintain their elegance and don't budge.

List<String> favoriteColors = const ['Blue', 'Green', 'Red'];

In this case, our favorite colors list is immutable. You can't add Purple, remove Green, or change Red to Yellow. It stays constant like a beautiful garden view.

Choosing Between the Two: Dance or Serenity?

Deciding between Mutable and Immutable Lists depends on your needs. If your list is a dynamic guest list, changing frequently, go for Mutable. But if you want a set collection that remains unchanged, opt for Immutable.

It's like choosing between a lively dance floor where the playlist evolves or a peaceful garden with timeless beauty. Dart collections offer you both, so whether you're into party vibes or serene elegance, there's a list for you!

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!