prefer_immediate_return
v0.8.0 Warning Fix Code Quality
This rule flags a local variable that is declared and then returned on the very next line, with no other use.
Why use this rule
Section titled “Why use this rule”The variable adds a name but no information — the return statement already says what the value is for. It also adds a line that has to be kept in sync: rename the variable and two places change instead of none.
Future<User> loadUser(String id) async { final user = await repository.fetchUser(id); return user;}Future<User> loadUser(String id) async { return repository.fetchUser(id);}Known limitations
Section titled “Known limitations”The rule reports only when the variable is provably throwaway:
- It is the second-to-last statement, directly followed by
return name;. - The declaration declares exactly one variable —
var a = 1, b = 2;is skipped. - It has an initializer and is not
late. - The returned identifier resolves to that declaration, not a field or outer variable with the same name.
- The variable is referenced exactly once in the whole function body — the return itself.
A variable kept deliberately as documentation (final isEligible = ...; return isEligible;) will be reported. If the name earns its place, suppress the diagnostic on that line.
Configuration
Section titled “Configuration”This rule is in the opinionated preset, so it is on with
preset: opinionated, or by name:
rules: prefer_immediate_return: trueTo turn it off again:
rules: prefer_immediate_return: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”prefer_early_return— Replace a body-wrapping if with an early-return guard.avoid_collapsible_if— Merge nested if statements with &&.avoid_redundant_else— Drop the else when the if branch always exits.avoid_accessing_other_classes_private_members— Make the underscore mean what everyone reads it as.