Skip to main content

switch_on_type

Learn about the switch_on_type linter rule.

Stable

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