switch_on_type
Avoid switch statements on a 'Type'.
Details
#AVOID using switch on Type
.
Switching on Type
is not type-safe and can lead to bugs if the class hierarchy changes. Prefer to use pattern matching on the variable instead.
BAD:
void f(Object o) {
switch (o.runtimeType) {
case int:
print('int');
case String:
print('String');
}
}
GOOD:
void f(Object o) {
switch(o) {
case int():
print('int');
case String _:
print('String');
default:
print('other');
}
}
Enable
#To enable the switch_on_type
rule, add switch_on_type
under linter > rules in your analysis_options.yaml
file:
linter:
rules:
- switch_on_type
If you're instead using the YAML map syntax to configure linter rules, add switch_on_type: true
under linter > rules:
linter:
rules:
switch_on_type: true
Unless stated otherwise, the documentation on this site reflects Dart 3.8.0. Page last updated on 2025-03-07. View source or report an issue.