Debug School

rakesh kumar
rakesh kumar

Posted on

Dart/Flutter List Tutorial with Examples

  1. How to create, initialize, access, modify, remove items in a List
  2. Ways to iterate, find, filter, transform items of a List in Dart/Flutter
  3. How to create List of objects in Dart/Flutter
  4. Ways to sort a List (of objects) in Dart/Flutter
  5. Initialize, iterate, flatten list of Lists

Important points about Dart List

These are some important information you should know before working with Dart List:

  1. There are kinds of List: fixed-length list (list’s length cannot be changed) & growable list (size can be changed to accommodate new items or remove items).
  2. Dart List is an ordered collection which maintains the insertion order of the items.
  3. Dart List allows duplicates and null values.
  4. While an operation on the list is being performed, modifying the list’s length (adding or removing items) will break the operation.

Create a List in Dart/Flutter

The example shows you:

How to create a List using List() constructor or literal syntax.
How to add new items to a List.
Create fixed-length list in Dart/Flutter

List<String> myList = List<String>(3);
myList[0] = 'one';
myList[1] = 'two';
myList[2] = 'three';
// myList.add('four');
/* throw UnsupportedError
(Unsupported operation: Cannot add to a fixed-length list) */
print(myList);
Enter fullscreen mode Exit fullscreen mode

Output:

[one, two, three]

var myList = List(3);
myList[0] = 'one';
myList[1] = 2;
myList[2] = null;
print(myList);
Enter fullscreen mode Exit fullscreen mode

Output:

[one, 2, null]

Create growable list in Dart/Flutter

We can create** growable list by not specify the length of the List**:

List<int> myList = List<int>();
myList.add(42);
myList.add(2018);
print(myList);
print(myList.length);
myList.add(2019);
print(myList);
print(myList.length);
Enter fullscreen mode Exit fullscreen mode

Output:

[42, 2018]
2
[42, 2018, 2019]
3

For growable list, Dart also allows literal syntax and null value:

var myList = List(); // var myList = [];
myList.add(42);
myList.add(null);
print(myList);
print(myList.length);
myList.add('year 2019');
print(myList);
print(myList.length);
Enter fullscreen mode Exit fullscreen mode

Output:

[42, null]
2
[42, null, year 2019]
3

Dart/Flutter initialize List with values

The examples show you how to:

  1. initialize list in simple way using operator [].
  2. create and fill a list with specified value using filled() constructor.
  3. create a list containing all specified itemsusing from() constructor.
  4. create a ‘const’ list using unmodifiable() constructor.
  5. create and fill a list with values by a generator function using generate() constructor.
List<int> intList = [1, 2, 3];
print(intList);
var myList = ['one', 2];
print(myList);
Output:
[1, 2, 3]
[one, 2]
// by default, growable: false
var fixedList = List.filled(3, 1);
print(fixedList);
// fixedList.add(42);
/*
UnsupportedError (Unsupported operation: Cannot add to a fixed-length list)
*/
var growableList = List.filled(3, 2, growable: true);
growableList.add(42);
print(growableList);
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 1, 1]
[2, 2, 2, 42]

// by default, growable: true
var fixedList = List.from([1, 2, 3], growable: false);
print(fixedList);
// fixedList.add(42);
/*
UnsupportedError (Unsupported operation: Cannot add to a fixed-length list)
*/
var growableList = List.from([1, 2, 3]);
growableList.add(42);
print(growableList)
Enter fullscreen mode Exit fullscreen mode

;
Output:

[1, 2, 3]
[1, 2, 3, 42]

var unmodifiableList = List.unmodifiable([1, 2, 3]);
print(unmodifiableList);
// unmodifiableList.add(42);
/*
UnsupportedError (Unsupported operation: Cannot add to an unmodifiable list)
*/
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
// by default, growable: true
var myList = List.generate(5, (index) => index * 2);
print(myList);
Enter fullscreen mode Exit fullscreen mode

Output:

[0, 2, 4, 6, 8]

Combine Lists in Dart/Flutter

  1. from() and addAll() method
  2. expand() method
  3. operator +
  4. spread operator ... or null-aware spread operator ...? (from Dart 2.3)
var list1 = [1, 2, 3];
var list2 = [4, 5];
var list3 = [6, 7, 8];
// from() and addAll() method
var combinedList1= List.from(list1)..addAll(list2)..addAll(list3);
// expand() method
var combinedList2 = [list1, list2, list3].expand((x) => x).toList();
// operator +
var combinedList3  = list1 + list2 + list3;
// spread operator
var combinedList4 = [...list1, ...list2, ...list3];
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 2, 3, 4, 5, 6, 7, 8]
Now, what if there is one of 3 lists above is a null list:

var list1 = [1, 2, 3];
var list2 = null;
var list3 = [6, 7, 8];
If we use any methods above to combine these lists, the program will throw an Exception:
– NoSuchMethodError: The getter 'iterator' was called on null.
– or: NoSuchMethodError: The getter 'length' was called on null.
Enter fullscreen mode Exit fullscreen mode

This is why null-aware spread operator ...? came to us. The operator check null list automatically with only one more ? symbol to be added:

var combinedList5 = [...?list1, ...?list2, ...?list3];
Output:

[1, 2, 3, 6, 7, 8]
Access items from List in Dart/Flutter
The examples show you how to:

find the size of a List using .length getter.
check if a List is empty or not using the getters: .isEmpty or .isNotEmpty. DON’T use .length.
access the item at specified index in a List using elementAt() method or operator [].
modify the item at specified index in a List using operator [].
get a group of items by specifying the range in List using getRange() method.
get the first count items of a List using take(count)

var myList = [0, 'one', 'two', 'three', 'four', 'five'];
myList.isEmpty;                       // false
myList.isNotEmpty;                    // true
myList.length;                        // 6
myList.elementAt(2);                  // two
myList[2];                            // two
myList[myList.length - 1];            // five
myList[3] = 3;                        // myList: [0, one, two, 3, four, five]
myList.getRange(1, 3).toList();       // [one, two]
myList.take(3).toList()               // [0, one, two]
Enter fullscreen mode Exit fullscreen mode

Remove items from List in Dart/Flutter
The examples show you how to:

remove the item at a given index in a List | removeAt(int index)
remove a item from a List by its value | remove(Object value)
remove all the items that match a given condition | removeWhere(bool test)
remove all the items in the range of a List | removeRange(int start, int end)
clear a List | clear()

var myList = [0, 'one', 'two', 'three', 'four', 'five'];
// remove the item at index '3'
myList.removeAt(3);
/* myList:
[0, one, two, four, five]
*/
// remove() returns false if the item does not exist in the List
bool isRemoved = myList.remove('three');
/* isRemoved:
false
*/
bool isRemoved4thItem = myList.remove('four');
/* isRemoved4thItem :
true
myList:
[0, one, two, five]
*/
// remove all items which length > 3
myList.removeWhere((item) => item.toString().length > 3);
/* myList:
[0, one, two]
*/
// remove all items in the List
myList.clear();
/* myList:
[]
*/
var anotherList = [0, 'one', 'two', 'three', 'four', 'five'];
// remove items from index 2 to 4
anotherList.removeRange(2, 5);
/* myList:
[0, one, five]
*/
Enter fullscreen mode Exit fullscreen mode

Update List item in Dart/Flutter

You can also update one or some items in a List using:

the item’s index
replaceRange() method to remove the objects in a range, then insert others

var myList = [0, 'one', 'two', 'three', 'four', 'five'];
// replace the item at index '3'
myList[3] = 3;
/* myList:
[0, one, two, 3, four, five]
*/
// replace the item at index '1'
myList.replaceRange(1, 2, [1]);
/* myList:
[0, 1, two, 3, four, five]
*/
// replace the items from index 2 to 4
myList.replaceRange(2, 5, ['new 2', '3 and 4']);
/* myList:
[0, 1, new 2, 3 and 4, five]
*/
Enter fullscreen mode Exit fullscreen mode

Iterate over List in Dart/Flutter

The examples show you how to iterate over a Dart List using:

  1. forEach() and lambda expression.
  2. iterator property to get Iterator that allows iterating.
  3. every() method
  4. simple for-each loop
  5. for loop with item index
var myList = [0, 'one', 'two', 'three', 'four', 'five'];
// use forEach()
myList.forEach((item) => print(item));
// or
myList.forEach(print);
// use iterator
var listIterator = myList.iterator;
while (listIterator.moveNext()) {
  print(listIterator.current);
}
// use every()
myList.every((item) {
  print(item);
  return true;
});
// simple for-each
for (var item in myList) {
  print(item);
}
// for loop with item index
for (var i = 0; i < myList.length; i++) {
  print(myList[i]);
}
Enter fullscreen mode Exit fullscreen mode

Dart/Flutter find elements in List

The examples show how to:

  1. check if a List contains an element or not | contains()
  2. find the index of the first occurrence of an element | indexOf()
  3. find the index of the last occurrence of an element | lastIndexOf()
  4. find the index of the first occurrence of an element that matches a condition | indexWhere()
  5. find the index of the last occurrence of an element that matches a condition | lastIndexWhere()
var myList = [0, 2, 4, 6, 8, 2, 8];
myList.contains(2);                        // true
myList.contains(5);                        // false
myList.indexOf(2);                         // 1
myList.lastIndexOf(2);                     // 5
myList.indexWhere((item) => item > 5);     // 3
myList.lastIndexWhere((item) => item > 5); // 6
Enter fullscreen mode Exit fullscreen mode

Filter items for a List in Dart/Flutter

The examples show how to:

filter all items in List that match the condition | where()
get the first item in List that matches the condition | firstWhere()
get the last item in List that matches the condition | lastWhere()
var myList = [0, 2, 4, 6, 8, 2, 7];
myList.where((item) => item > 5).toList();   // [6, 8, 7]
myList.firstWhere((item) => item > 5);       // 6
myList.lastWhere((item) => item > 5);        // 7
Enter fullscreen mode Exit fullscreen mode

Dart/Flutter List every
We can verify if all items in a List satisfy a condition using every() method.

var intList = [5, 8, 17, 11];
if (intList.every((n) => n > 4)) {
  print('All numbers > 4');
}
Enter fullscreen mode Exit fullscreen mode

Dart/Flutter List any
We can verify if at least one item in a List satisfies a condition using any() method.

var intList = [5, 8, 17, 11];
if (intList.any((n) => n > 10)) {
  print('At least one number > 10');
}
Enter fullscreen mode Exit fullscreen mode

Dart/Flutter List map items into new List
We can map each item in a Dart List to new form using map() method:

var myList = ['zero', 'one', 'two', 'three', 'four', 'five'];
var uppers = myList.map((item) => item.toUpperCase()).toList();
/*
myList: [zero, one, two, three, four, five]
uppers: [ZERO, ONE, TWO, THREE, FOUR, FIVE]
*/
Enter fullscreen mode Exit fullscreen mode

User defined objects List in Dart/Flutter

In Dart, we can create a List of any type, from int, double, String, to complex types like a List, Map, or any user defined objects.

The example show how to create a List of user defined object:

class Customer {
  String name;
  int age;
  Customer(this.name, this.age);
  @override
  String toString() {
    return '{ ${this.name}, ${this.age} }';
  }
}
main() {
  List customers = [];
  customers.add(Customer('Jack', 23));
  customers.add(Customer('Adam', 27));
  customers.add(Customer('Katherin', 25));
  print(customers);
  print(customers.length);
}
Enter fullscreen mode Exit fullscreen mode

Output:

[{ Jack, 23 }, { Adam, 27 }, { Katherin, 25 }]
3

Dart/Flutter List collection if and collection for
With the collection if and collection for, we can dynamically create lists using conditionals (if) and repetition (for).

var mobile = true;
var web = false;
var tringList = ['kotlin', 'dart', if (mobile) 'flutter', if (web) 'react'];
// [kotlin, dart, flutter]
var intList = [for (var i = 1; i < 10; i++) i];
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
var evenList = [
  for (var i = 1; i < 10; i++)
    if (i % 2 == 0) i
];
// [2, 4, 6, 8]
Sort List in Dart/Flutter
The examples show you how to:

sort a List using sort() method.
sort a List of objects using custom compare function.
sort a List of objects by extending Comparable abstract class.
Sort List using sort() method
var intList = [0, 5, 2, 3, 8, 17, 11];
intList.sort();
print(intList);
var tringList = ['vue', 'kotlin','dart', 'angular', 'flutter'];
tringList.sort();
print(tringList);
Enter fullscreen mode Exit fullscreen mode

Output:

[0, 2, 3, 5, 8, 11, 17]
[angular, dart, flutter, kotlin, vue]
Sort a List of objects in Dart/Flutter
For more details, please visit: Dart/Flutter – Sort list of Objects

- use custom compare function:

class Customer {
  String name;
  int age;
  Customer(this.name, this.age);
  @override
  String toString() {
    return '{ ${this.name}, ${this.age} }';
  }
}
main() {
  List customers = [];
  customers.add(Customer('Jack', 23));
  customers.add(Customer('Adam', 27));
  customers.add(Customer('Katherin', 25));
  customers.sort((a, b) => a.age.compareTo(b.age));
  print('Sort by Age: ' + customers.toString());
  customers.sort((a, b) => a.name.compareTo(b.name));
  print('Sort by Name: ' + customers.toString());
}
Enter fullscreen mode Exit fullscreen mode

Output:

`Sort by Age: [{ Jack, 23 }, { Katherin, 25 }, { Adam, 27 }]
Sort by Name: [{ Adam, 27 }, { Jack, 23 }, { Katherin, 25 }]

  • The second approach is to extend Comparable abstract class and override compareTo() method. Now we don't need to pass compare function, we just call list.sort() instead of list.sort(compare).`
class Customer extends Comparable {
  String name;
  int age;
  Customer(this.name, this.age);
  @override
  String toString() {
    return '{ ${this.name}, ${this.age} }';
  }
  // sort by Name (asc), then age (desc)
  @override
  int compareTo(other) {
    int nameComp = this.name.compareTo(other.name);
    if (nameComp == 0) {
      return -this.age.compareTo(other.age); // '-' for descending
    }
    return nameComp;
  }
}
main() {
 List customers = [];
  customers.add(Customer('Jack', 23));
  customers.add(Customer('Adam', 27));
  customers.add(Customer('Katherin', 25));
  customers.add(Customer('Jack', 32));
  customers.sort();
  print(customers);
}
Enter fullscreen mode Exit fullscreen mode

Output:

[{ Adam, 27 }, { Jack, 32 }, { Jack, 23 }, { Katherin, 25 }]

Dart/Flutter List reverse

We can reverse a list using reversed property. It returns an Iterable of the objects in the list.

var tringList = ['vue', 'kotlin','dart', 'angular', 'flutter'];
var reversed = List.of(tringList.reversed);
// [flutter, angular, dart, kotlin, vue]
Enter fullscreen mode Exit fullscreen mode

Dart/Flutter List of Lists

Initialize List of Lists
We will:

initialize list of existing lists using operator [].
create and fill list of lists with values by a generator function using generate() constructor.

var list1 = [1, 2];
var list2 = [3, 4];
var list3 = [5, 6];
var listOfLists = [list1, list2, list3];
// [[1, 2], [3, 4], [5, 6]]
List> listOfNumbers =
    List.generate(3, (i) => [i * 2 + 1, i * 2 + 2]);
// [[1, 2], [3, 4], [5, 6]]
Enter fullscreen mode Exit fullscreen mode

Iterate List of Lists

The examples show you how to iterate over a Dart List using:

  1. forEach() and lambda expression.
  2. every() method
  3. simple for-each loop
  4. for loop with item index
var listOfNumbers = [[1, 2], [3, 4, 5], [6, 7, 8]];
listOfNumbers.forEach((nums) => nums.forEach((number) => print(number)));
listOfNumbers.every((nums) {
  nums.forEach((number) => print(number));
  return true;
});
for (var nums in listOfNumbers) {
  for (var number in nums) {
    print(number);
  }
}
for (var i = 0; i < listOfNumbers.length; i++) {
  for (var j = 0; j < listOfNumbers[i].length; j++) {
    print(listOfNumbers[i][j]);
  }
}
Enter fullscreen mode Exit fullscreen mode

/* Result:
1
2
3
4
5
6
7
8
*/

Flatten List of Lists

The examples show you how to flatten a Dart list of lists using:

combination of forEach() and addAll() method.
Iterator expand() method.
var listOfNumbers = [[1, 2], [3, 4, 5], [6, 7, 8]];
var flattenList1 = [];
listOfNumbers


    .forEach((nums) => nums.forEach((number) => flattenList1.add(number)));
// [1, 2, 3, 4, 5, 6, 7, 8]
var flattenList2 = [];
flattenList2 = listOfNumbers.expand((number) => number).toList();
// [1, 2, 3, 4, 5, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

Full Summary

  1. Create fixed-length list in Dart/Flutter(string example)
  2. Create growable list in Dart/Flutter(int example)=add,length
  3. Dart/Flutter initialize List with values(filled,add,unmodifiable)
  4. Combine Lists in Dart/Flutter(from(), and addAll() method,expand(), method operator + ,spread operator ... or null-aware spread operator ...?.
  5. Access items from List in Dart/Flutter(.length,.isEmpty or .isNotEmpty,elementAt(),operator [],getRange() ,take(count).
  6. Remove items from List in Dart/Flutter-(removeAt(int index)
  7. remove(Object value),removeWhere(bool test),removeRange(int start, int end), clear(),var myList = [0, 'one').
  8. Update List item in Dart/Flutter(tem’s index,replaceRange() )
  9. Iterate over List in Dart/Flutter(forEach(),iterator ,every() method,for-each loop,for loop with item index)
  10. Dart/Flutter find elements in List(c ontains(),indexOf(),lastIndexOf(),indexWhere(),lastIndexWhere())
  11. Filter items for a List in Dart/Flutter( where(),firstwhere,lastwhere)
  12. Dart/Flutter List every
  13. Dart/Flutter List any
  14. Dart/Flutter List map items into new List(toUpperCase())
  15. User defined objects List in Dart/Flutter(add)
  16. Dart/Flutter List collection if and collection for(create lists using conditionals (if) and repetition (for).)
  17. Sort List in Dart/Flutter(sort a List using sort() method.,compare)
  18. Sort List using sort() method(
  19. Sort a List of objects in Dart/Flutter(add,compareTo)
  20. Dart/Flutter List reverse
  21. Dart/Flutter List of Lists(operator [],generator)
  22. Iterate List of Lists(forEach() and lambda expression.
  23. every() method,simple for-each loop,for loop with item index)
  24. Flatten List of Lists

Refrence

Top comments (0)