Introduction
In Flutter/Dart, there are situations when we need to find elements in a List. In this post, we'll look at how to do it.
How to find elements in List in Flutter
In Flutter/Dart we have several methods that allow us to find element/elements in a List.
Using contains()
method to check if a list contains an element or not
var list = [0, 1, 2, 3];
print(list.contains(2)); // true
print(list.contains(4)); // false
The output:
true
false
Using theindexOf()
method to find the index of the first occurrence of an element
var list = [0, 1, 2, 3];
print(list.indexOf(2)); // 2
The output:
2
Using lastIndexOf()
method to find the index of last occurence of an element
var list = [0, 1, 2, 3, 2, 1, 0];
print(list.lastIndexOf(0)); // 6
The output:
6
Using theindexWhere()
method to find the index of the first element that matches a specific condition
var list = [0, 1, 2, 3, 2, 1, 0];
print(list.indexWhere((item) => item > 1)); // 2
The output:
2
Using thelastIndexWhere()
method to find the index of the last element that matches given condition
var list = [0, 1, 2, 3, 2, 1, 0];
print(list.lastIndexWhere((item) => item > 1)); // 4
The output:
4
Conclusion
In this article, we presented several ways to find element/elements in a list in Flutter/Dart.
Check more valuable articles about Lists in Flutter:
- Filter items in a List in Flutter/Dart
- Sort a List in Flutter/Dart
- FlatMap a list of lists in Flutter/Dart
- Reverse a List in Flutter/Dart
- Iterate over List in Flutter/Dart
- Remove items from a List in Flutter/Dart
- Access items from List in Flutter/Dart
- Create a list in Flutter/Dart
- Combine Lists in Flutter/Dart
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}