Skip to main content
1

๐Ÿ” Ends of the List

firstOrNull
T?
Gets the first element of the list, or returns null if the list is empty. Prevents StateError.
final numbers = [1, 2, 3];
final result = numbers.firstOrNull;  // 1

final alphabets = [];
final last = alphabets.firstOrNull; // null
lastOrNull
T?
Gets the last element of the list, or returns null if the list is empty. Prevents StateError.
final names = ['Alice', 'Bob'];
final last = names.lastOrNull; // 'Bob'

final ids = [];
final last = ids.lastOrNull; // null
2

๐Ÿ” Index & Element Access

elementAtOrNull(int index)
T?
Safely retrieves an element at a given index, returning null if the index is out of bounds. Prevents RangeError.
final data = ['a', 'b', 'c'];
final safe = data.elementAtOrNull(10); // null
indexOfOrNull(T element)
int?
Gets the index of the element, or returns null if the element doesnโ€™t exist in the list.
final ids = [10, 20, 30];
final notFound = ids.indexOfOrNull(50); // null
firstWhereOrNull(bool Function(T) test)
T?
Gets the first element that satisfies the test, or returns null if none is found. Prevents StateError without needing an orElse callback.
final users = [{'id': 1}, {'id': 2}];
final missing = users.firstWhereOrNull((u) => u['id'] == 99); // null