List in Dart

List in Dart

In Dart, Collections are used to store data. The list is a collection of data having the same data type. In other languages, the List is called Array.

·

6 min read

Consider a situation where we need to store five String values. If we use programming’s simple variable and data type concepts, then we need five variables of String data type.

It seems simple because we had to store just five String values. Now let’s assume we have to store 10000 String values. Now it's too time-consuming to create 10000 variables.

  • To overcome this kind of situation we have a concept called Collections.

  • Collections are used to store data.

In Dart, collections can be classified into four basic categories:

  • List

  • Map

  • Set

  • Queue

But the list and map are mostly used. Set and queue are used in some special cases.

List

  • A list is a collection of data. In other languages, it is called an Array.

  • In a list, data is stored in an ordered way. Every individual element of the list can be accessed by its index number. The index number always starts from 0.

Creating a List in Dart

You can create a list using two syntaxes: the literal form and the constructor form.

1. Literal Syntax

var colors = ["Blue", "Yellow", "Brown"];

Here, we have a list of strings, and the type of the list is inferred as List<String>

2. Constructor Syntax

var numbers = List<int>.empty(growable: true); // Empty, growable list
numbers.add(10);
numbers.add(20);

The second syntax allows you to specify the type of elements the list will hold, ensuring type safety.

Commonly Used List Methods in Dart

Dart provides a range of methods that allow you to manipulate and query lists efficiently. Below are some of the most commonly used methods:

1. add(element)

This method adds an element to the end of the list.

var colors = ['blue', 'red'];
colors.add('orange');
print(colors); // Output - [blue, red, orange]

2. addAll(iterable)

Adds all elements of an iterable to the list.

var colors = ['blue'];
colors.addAll(['red', 'orange']);
print(colors); // Output - [blue, red, orange]

3. insert(index, element)

Inserts an element at the specified index.

var colors = ['blue', 'red'];
colors.insert(1, 'orange');
print(colors); // [blue, red, orange]

4. insertAll(index, iterable)

Inserts all elements of an iterable starting at the specified index.

var colors = ['blue', 'orange'];
colors.insertAll(1, ['red', 'gray']);
print(colors); // [blue, red, gray, orange]

5. remove(element)

Removes the first occurrence of the element from the list. Note here only the First occurrence not all occurrences will be removed.

var colors = ['blue', 'pink', 'orange'];
colors.remove('pink');
print(colors); // [blue, orange]

6. removeAt(index)

Removes the element at the specified index and returns it.

var colors = ['blue', 'pink', 'orange'];
var removedColors = colors.removeAt(1);
print(removedColors); // pink
print(colors);       // [blue, orange]

7. removeLast()

Removes and returns the last element in the list.

var colors = ['blue', 'pink', 'orange'];
var lastColor = colors.removeLast();
print(lastColor); // orange
print(colors);    // [blue, pink]

8. removeWhere(condition)

Removes all elements that satisfy the provided condition.

var numbers = [10, 20, 30, 40, 50];
numbers.removeWhere((number) => number > 30);
print(numbers); // [10, 20, 30]

9. contains(element)

Checks if the list contains the specified element.

var colors = ['blue', 'pink'];
print(colors.contains('pink')); // true

10. indexOf(element)

Returns the first index of the specified element in the list. If the element is not found, it returns -1.

var colors = ['blue', 'pink', 'orange'];
print(colors.indexOf('pink')); // 1

11. sort()

Sorts the list in place using natural ordering for the type of elements.

Here natural ordering means Numbers in Ascending Order and Alphabets from A to Z.

var colors = ['blue', 'pink', 'orange'];
colors.sort();
print(colors); // [blue, pink, orange]

12. reversed

Returns an iterable that iterates over the elements in reverse order.

var colors = ['blue', 'pink', 'orange'];
var reversedColors = colors.reversed;
print(reversedcolors); // (orange, pink, blue)

13. join([separator])

Returns a string concatenation of all elements in the list, separated by the optional separator.

var colors = ['blue', 'pink', 'orange'];
var colorsString = colors.join(', ');
print(colorsString); // blue, pink, orange

14. map(function)

Returns a new array with elements transformed by the provided function.

var numbers = [1, 2, 3];
var doubled = numbers.map((n) => n * 2);
print(doubled); // (2, 4, 6)

15. sublist(start, end)

Returns a sublist starting at the start index and extending to (but not including) the optional end index.

var colors = ['blue', 'pink', 'orange', 'yellow'];
var subColors = colors.sublist(1, 3);
print(subColors); // [pink, orange]

16. forEach(action)

Iterates over each element and performs an action.

var colors= ['blue', 'pink', 'orange', 'yellow'];
colors.forEach((color) => print(color));

// blue
// pink
// orange
// yellow

Important Note

Certain Array methods might manipulate your original array. So as a developer, you must know which methods will manipulate your original array or which will not.

Array Methods that Modifies the Original List

  • add(element)

  • addAll(iterable)

  • insert(index, element)

  • insertAll(index, iterable)

  • remove(element)

  • removeAt(index)

  • removeLast()

  • removeWhere(test)

  • sort()

Methods that Create a New Arrya / Returns a New Value

  • map(transform) (returns a new iterable)

  • where(test) (returns a new iterable)

  • sublist(start, [end]) (returns a new list)

  • reversed (returns a new iterable)

  • join([separator]) (returns a string)

  • indexOf(element) (returns an index or -1)

  • contains(element) (returns a boolean)

Conclusion

Dart’s List class provides a powerful and flexible way to work with collections of data. With its vast array of methods, you can add, remove, sort, and manipulate elements efficiently. Whether you're creating small utility scripts or large-scale applications, mastering these list methods will enable you to write more effective and optimized Dart code.

So, guys, That’s it for a list. As I always say practice it, understand it conceptually. Till then Keep Loving, Keep Coding. And just like always I’ll surely catch you up in the next article. 😊

Remember no teacher, no book, no video tutorial, or no blog can teach you everything. As one said Learning is Journey and Journey never ends. Just collect some data from here and there, read it, learn it, practice it, and try to apply it. Don’t feel hesitant that you can’t do that or you don’t know this concept or that concept. Remember every programmer was passed from the path on which you are walking right now. Remember Every Master was Once a Beginner. Work hard and Give your best.

Learn More about Dart and Flutter

Follow me for more such content

Did you find this article valuable?

Support Jay Tillu by becoming a sponsor. Any amount is appreciated!