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:
dart
void f(Object o) {
switch (o.runtimeType) {
case int:
print('int');
case String:
print('String');
}
}
GOOD:
dart
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:
analysis_options.yaml
yaml
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:
analysis_options.yaml
yaml
linter:
rules:
switch_on_type: 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.