Flutter firstWhereOrNull()
The firstWhereOrNull()
method in Flutter returns the first element in a collection that satisfies the specified condition. If no element is found, it returns null
. This method can be used with various collections like lists, sets, or maps.
Syntax:
T? firstWhereOrNull(bool test(T element), { T orElse()? })
Parameters:
test – A function that takes an element from the collection as an argument and returns a boolean value indicating whether it satisfies the condition.
orElse – An optional function that returns a default value if no element satisfies the condition.
Return Value:
The first element that satisfies the condition, or null
if no element is found and no orElse
function is provided.
Example:
void main() {
List numbers = [1, 2, 3, 4, 5];
int? number = numbers.firstWhereOrNull((int element) => element > 3);
print(number); // Output: 4
String? name = numbers.firstWhereOrNull((int element) => element > 10, orElse: () => 'Not Found');
print(name); // Output: Not Found
}
In the example, we have a list of numbers and we want to find the first number greater than 3. Using the firstWhereOrNull()
method, we pass a lambda function that checks if the element is greater than 3. The return value is assigned to the number
variable, and we print it to the console.
If we want to handle the case when no number satisfies the condition, we can provide an orElse
function. In the second firstWhereOrNull()
call, we set the element > 10
condition, which is not satisfied by any number in the list. Therefore, the orElse
function is executed and returns the string ‘Not Found’.