prefer_enums_by_name
v0.4.0 Warning Fix Collection & Type
Using .firstWhere((e) => e.name == value) on enum values can be replaced with the built-in .byName() method, available since Dart 2.15. The dedicated method is more concise, more readable, and throws a clear ArgumentError when the name is not found.
Why use this rule
Section titled “Why use this rule”.byName() was specifically designed for looking up enum values by their string name. It is shorter, self-documenting, and provides a better error message on failure compared to the firstWhere approach which throws a generic StateError.
See also: Dart enums
enum Style { standard, express, overnight }
void example() { // Use .byName() instead of .firstWhere() final style = Style.values.firstWhere( (speed) => speed.name == 'express', );
// Reversed comparison also detected final style2 = Style.values.firstWhere( (speed) => 'overnight' == speed.name, );
// Variable comparison final name = 'underline'; final style3 = Style.values.firstWhere((speed) => speed.name == name);}enum Style { standard, express, overnight }
void example() { final style = Style.values.byName('express');
final name = 'underline'; final style2 = Style.values.byName(name);}Configuration
Section titled “Configuration”This rule is in the recommended preset, so it is on with
preset: recommended or preset: opinionated. Add it to preset: core with
prefer_enums_by_name: true.
To turn it off:
rules: prefer_enums_by_name: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”avoid_missing_enum_constant_in_map— Cover every enum constant in a map keyed by that enum.enum_constants_ordering— Keep enum constants in a configured order.avoid_accessing_collections_by_constant_index— Avoid accessing a collection by a constant index inside a loop.avoid_collection_equality_checks— Avoid comparing collections with == or != as it checks reference equality, not contents.