One of the most popular data structure in OOP is List. In this tutorial, we’ll show you many methods and functions to work with a List in Dart (also in Flutter). At the end, you’re gonna know:
- Introduction to Dart List
- How to create, initialize, access, modify, remove items in a List
- Ways to iterate, find, filter, transform items of a List in Dart/Flutter
- How to create List of objects in Dart/Flutter
- Ways to sort a List (of objects) in Dart/Flutter
- Initialize, iterate, flatten list of Lists
Related Posts:
– Dart/Flutter – Convert Object to JSON string
– Dart/Flutter – Convert/Parse JSON string, array into Object, List
– Dart/Flutter – Convert List to Map & Map to List
– Dart – Convert Object to Map and Vice Versa
– Dart/Flutter – Sort list of Objects
– Dart/Flutter Constructors tutorial with examples
– Dart/Flutter String Methods & Operators tutorial with examples
– Dart/Flutter Future Tutorial with Examples
– Dart/Flutter Map Tutorial with Examples
Contents
- Important points about Dart List
- Create a List in Dart/Flutter
- Dart/Flutter initialize List with values
- Combine Lists in Dart/Flutter
- Access items from List in Dart/Flutter
- Remove items from List in Dart/Flutter
- Update List item in Dart/Flutter
- Iterate over List in Dart/Flutter
- Dart/Flutter find elements in List
- Filter items for a List in Dart/Flutter
- Dart/Flutter List every
- Dart/Flutter List any
- Dart/Flutter List map items into new List
- User defined objects List in Dart/Flutter
- Dart/Flutter List collection if and collection for
- Sort List in Dart/Flutter
- Dart/Flutter List reverse
- Dart/Flutter List of Lists
- Conclusion
- Further Reading
Important points about Dart List
These are some important information you should know before working with Dart List:
- 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)
- Dart List is an ordered collection which maintains the insertion order of the items.
- Dart List allows duplicates and
null
values. - 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);
Output:
[one, two, three]
Dart also allows literal syntax and null
value:
var myList = List(3);
myList[0] = 'one';
myList[1] = 2;
myList[2] = null;
print(myList);
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);
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);
Output:
[42, null]
2
[42, null, year 2019]
3
Dart/Flutter initialize List with values
The examples show you how to:
- initialize list in simple way using operator
[]
. - create and fill a list with specified value using filled() constructor.
- create a list containing all specified itemsusing from() constructor.
- create a ‘const’ list using unmodifiable() constructor.
- 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);
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);
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)
*/
Output:
[1, 2, 3]
// by default, growable: true
var myList = List.generate(5, (index) => index * 2);
print(myList);
Output:
[0, 2, 4, 6, 8]
Combine Lists in Dart/Flutter
The examples show how to combine Lists using:
- from() and addAll() method
expand()
method- operator
+
- 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];
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.
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]
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]
*/
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]
*/
Iterate over List in Dart/Flutter
The examples show you how to iterate over a Dart List using:
forEach()
and lambda expression.- iterator property to get
Iterator
that allows iterating. - every() method
- simple for-each loop
- 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]);
}
Dart/Flutter find elements in List
The examples show how to:
- check if a List contains an element or not | contains()
- find the index of the first occurrence of an element | indexOf()
- find the index of the last occurrence of an element | lastIndexOf()
- find the index of the first occurrence of an element that matches a condition | indexWhere()
- 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
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
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');
}
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');
}
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]
*/
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);
}
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);
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());
}
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);
}
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]
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]]
Iterate List of Lists
The examples show you how to iterate over a Dart List using:
forEach()
and lambda expression.every()
method- simple for-each loop
- 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]);
}
}
/* 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()
andaddAll()
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]
Conclusion
In this tutorial, we've learned overview of a Dart List, how to create a List, how to add, modify and remove items from a List, how to iterate over a List, how to combine Lists, transform, find, filter, sort items in a List along with List of objects.
Happy learning! See you again!
Further Reading
- Dart/Flutter Constructors tutorial with examples
- Dart/Flutter String Methods & Operators tutorial with examples
- Dart/Flutter Future Tutorial with Examples
- Dart/Flutter Map Tutorial with Examples
- Dart – Convert Object (List of Objects) to Map and Vice Versa
Many Thanks for your tutorial
This is precisely the kind of useful Dart tutorial that developers need. Well laid out and explained, with helpful examples.
Thank you for taking the time to write this
Thanks, this is very help full for us.
Thanks, I have recently been looking for this comprehensive Dart tutorial and found this one 🙂
Love the tutorial!
Full of knowledge about Dart List. Thanks! Will likeⅼy be back to see more tutorials.
Hеy therе! Thank you so much for your effort to make this Dart tutorial!
I have learnt a lot from your Dart Flutter tutorial.
issues or tips. Perhaps you can write subsequent articles relating to this Tutorial.
I wish to learn more things about Dart data structure from you.
Greetings! Very helpful Dart tutorial!
It’s the little changes thɑt make the most significant сhanges.
Many thanks for sharing!
Hi there! Ꭲhis is my firѕt comment here so I juѕt wаnted to telⅼ you I really enjoy readіng through your posts.
Thanks a ton!
I don’t know how many times I’ve opened this post in this week 😀
Sometimes it’s tricky working with List.
Thanks for a very complete post!
Hi, I’m so happy to know that my work helps people like you 🙂
thank you very much for providing such a detailed notes
Thanks u so much
Merci beaucoup pour votre aide
Wow! This is a wonderful tutorial, complete reference about Dart List. Thank you for your effort to make the tutorial.
Thanks for this complete reference about Dart List. I think you spent much time to create this tutorial. Wish you all the best!