avoid-unsafe-collection-methods
preset: recommended
Warns when first
, last
, single
, firstWhere
, lastWhere
, singleWhere
or []
methods are used on Iterable
or its subclasses.
Accessing elements via these methods can result in an exception being thrown at runtime, if there are no element found. To avoid that, use firstOrNull
, lastOrNull
, singleOrNull
, firstWhereOrNull
, lastWhereOrNull
, singleWhereOrNull
or elementAtOrNull
from the collection package instead.
note
The rule won't trigger on a []
used on a map.
Example
❌ Bad:
List<String> someList = [...];
someList.first; // LINT
someList.last; // LINT
someList.single; // LINT
someList.firstWhere(...); // LINT
someList.lastWhere(...); // LINT
someList.singleWhere(...); // LINT
if (someList case Set(:final first)) {} // LINT
if (someList case Set(first: final f)) {} // LINT
✅ Good:
List<String> someList = [...];
someList.firstOrNull;
someList.lastOrNull;
someList.singleOrNull;
someList.firstWhereOrNull(...);
someList.lastWhereOrNull(...);
someList.singleWhereOrNull(...);
if (someList case Set(:final firstOrNull)) {}
if (someList case Set(firstOrNull: final orNull)) {}
ListView.builder(
itemCount: nullable?.length ?? 0,
itemBuilder: (_, index) {
nullable[index];
},
);