Skip to main content

prefer_if_elements_to_conditional_expressions

Details about the 'prefer_if_elements_to_conditional_expressions' diagnostic produced by the Dart analyzer.

Use an 'if' element to conditionally add elements.

Description

#

The analyzer produces this diagnostic when a conditional expression is used as an element of a list or set literal and an if element could be used instead.

Example

#

The following code produces this diagnostic because a conditional expression is used to choose which of two values to include in the created list:

dart
List<String> f(bool b) {
  return ['a', b ? 'c' : 'd', 'e'];
}

Common fixes

#

Use an if element to select the value:

dart
List<String> f(bool b) {
  return ['a', if (b) 'c' else 'd', 'e'];
}