Skip to main content

avoid-unsafe-collection-methods

added in: 1.4.0
🛠
Pro+
preset: recommended

Warns when first, last, single, max, min, 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: Calling this method/property may throw an exception. Try using the safe 'firstOrNull' from 'package:collection' instead.
someList.last; // LINT: Calling this method/property may throw an exception. Try using the safe 'lastOrNull' from 'package:collection' instead.

someList.firstWhere(...); // LINT: Calling this method/property may throw an exception. Try using the safe 'firstWhereOrNull' from 'package:collection' instead.
someList.lastWhere(...); // LINT: Calling this method/property may throw an exception. Try using the safe 'lastWhereOrNull' from 'package:collection' instead.

if (someList case Set(:final first)) {} // LINT: Calling this method/property may throw an exception. Try using the safe 'firstOrNull' from 'package:collection' instead.
if (someList case Set(first: final f)) {} // LINT: Calling this method/property may throw an exception. Try using the safe 'lastOrNull' from 'package:collection' instead.

✅ Good:

List<String> someList = [...];

someList.firstOrNull; // Correct, safe access
someList.lastOrNull;

someList.firstWhereOrNull(...);
someList.lastWhereOrNull(...);

if (someList case Set(:final firstOrNull)) {}
if (someList case Set(firstOrNull: final orNull)) {}

ListView.builder(
itemCount: nullable?.length ?? 0,
itemBuilder: (_, index) {
nullable[index]; // Correct, only happens when 'nullable' has items
},
);

Additional Resources