use_enums
Use enums rather than classes that behave like enums.
Details
#Classes that look like enumerations should be declared as enum
s.
DO use enums where appropriate.
Candidates for enums are classes that:
- are concrete,
- are private or have only private generative constructors,
- have two or more static const fields with the same type as the class,
- have generative constructors that are only invoked at the top-level of the initialization expression of these static fields,
- do not define
hashCode
,==
,values
orindex
, - do not extend any class other than
Object
, and - have no subclasses declared in the defining library.
To learn more about creating and using these enums, check out Declaring enhanced enums.
BAD:
dart
class LogPriority {
static const error = LogPriority._(1, 'Error');
static const warning = LogPriority._(2, 'Warning');
static const log = LogPriority._unknown('Log');
final String prefix;
final int priority;
const LogPriority._(this.priority, this.prefix);
const LogPriority._unknown(String prefix) : this._(-1, prefix);
}
GOOD:
dart
enum LogPriority {
error(1, 'Error'),
warning(2, 'Warning'),
log.unknown('Log');
final String prefix;
final int priority;
const LogPriority(this.priority, this.prefix);
const LogPriority.unknown(String prefix) : this(-1, prefix);
}
Enable
#To enable the use_enums
rule, add use_enums
under linter > rules in your analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- use_enums
If you're instead using the YAML map syntax to configure linter rules, add use_enums: true
under linter > rules:
analysis_options.yaml
yaml
linter:
rules:
use_enums: true
Was this page's content helpful?
Thank you for your feedback!
Provide details Thank you for your feedback! Please let us know what we can do to improve.
Provide details Unless stated otherwise, the documentation on this site reflects Dart 3.8.1. Page last updated on 2025-03-07. View source or report an issue.