Skip to content

element_read_from_filter

Reports first, last, single or reduce on what a filter kept, where nothing shows it kept an element. Use firstOrNull, firstWhere with orElse, or a test instead.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
none

first, last, single or reduce of what a filter kept, where nothing around shows that it kept anything: items.where((item) => item.id == id).first. The violation is on the member’s name.

  • The filters are the SDK’s where, whereType, skipWhile, takeWhile and nonNulls.
  • The read is judged on the filter’s result, on what map, cast, toList, toSet, reversed or followedBy make of it, and on a local declared with one of them and not assigned again.

It does not report a read where a test of that code for its length or emptiness stands around it. The test can be of the result or of any step it is made of, down to the filter. It counts:

  • in the condition of an if (its when clause too), a conditional, a while, && or ||;
  • in an if or an assert before the read, in a block around it;
  • as the collection a for around the read goes over;
  • after an add or insert to it.

A test of the collection that was filtered says nothing of what the filter kept, so it does not count.

It does not report either a null-aware read, a filter of the project, or code on the test side of a project. Nor does it report firstWhere, lastWhere and singleWhere without orElse, which throw as well: they are the written form of a lookup known to succeed.

Each read throws a StateError when the filter kept no element, and single also when it kept more than one. After a filter, an empty result is a real possibility: an id that is not there, a type no element has. firstWhere with orElse, firstOrNull or a test make the empty case visible.

Violating
Item byId(List<Item> items, String id) =>
items.where((item) => item.id == id).first;
Corrected
Item? byId(List<Item> items, String id) =>
items.where((item) => item.id == id).firstOrNull;

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// Why it stays as written here.
// ignore: element_read_from_filter

// ignore_for_file: assay/element_read_from_filter silences it in a whole file, and // ignore: assay/element_read_from_filter with the prefix works too. See Suppressions.