Skip to main content

prefer-early-return

added in: 1.3.0
⚙️
Pro+

Warns when an if statement can be transformed to an early return.

Early returns help reducing the code nesting level, improving the overall readability.

⚙️ Config

Set ignore-if-case (default is false) to ignore if statements that have a case block (example).

analysis_options.yaml
dart_code_metrics:
rules:
- prefer-early-return:
ignore-if-case: false

Example

❌ Bad:

void someFunction() {
// LINT: Prefer an early return to a conditionally-wrapped block.
if (_value == 2) {
print('hello');
print(_value);
}
}

✅ Good:

void correct() {
if (_value != 2) {
return;
}

print('hello');
print(_value);
}

Example with "ignore-if-case"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- prefer-early-return:
ignore-if-case: true

✅ Good:

void correct() {
if (_value case int()) { // Correct, ignored
print('hello');
}
}