exhaustive_ cases
Details about the 'exhaustive_cases' diagnostic produced by the Dart analyzer.
Missing case clauses for some constants in '{0}'.
Description
#
The analyzer produces this diagnostic when a
switch statement over an instance of an enum-like type is
missing a case clause for one or more of the type's constants and
doesn't have a default clause.
Enum-like types are classes or extension types that have:
- Only private, non-factory constructors.
- Two or more
static constfields whose type is the enclosing type.
In addition, an enum-like class must be non-abstract and have no subclasses in the defining library.
Example
#
The following code produces this diagnostic because the
switch statement is missing a case clause for the constant
C.c:
class const C._(final int i) {
static const C a = ._(1);
static const C b = ._(2);
static const C c = ._(3);
}
void f(C c) {
switch (c) {
case .a:
print('a');
case .b:
print('b');
}
}
Extension types can also be enum-like. The following code produces this
diagnostic because the switch statement is missing a case
clause for
the constant E.b:
extension type const E._(int value) {
static const E a = ._(1);
static const E b = ._(2);
}
void f(E e) {
switch (e) {
case .a:
print('a');
}
}
Common fixes
#
If the missing constant needs to be handled separately,
then add a case clause for it:
class const C._(final int i) {
static const C a = ._(1);
static const C b = ._(2);
static const C c = ._(3);
}
void f(C c) {
switch (c) {
case .a:
print('a');
case .b:
print('b');
case .c:
print('c');
}
}
If the missing constant doesn't need to be handled specially,
then add a default clause to cover it:
class const C._(final int i) {
static const C a = ._(1);
static const C b = ._(2);
static const C c = ._(3);
}
void f(C c) {
switch (c) {
case .a:
print('a');
case .b:
print('b');
default:
print('other');
}
}
Unless stated otherwise, the documentation on this site reflects Dart 3.13.3. Report an issue.