always_returns_null
Reports a function with a nullable result that returns null on every way out. Return the value it was meant to give.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- strict
- Fix
- none
What it reports
Section titled “What it reports”A function, a method or a getter whose return type may be null and that always returns null: String? label() => null;. Its callers test for a value that never comes.
- The return type is written and nullable:
T?, or for anasyncfunction aFuture<T?>or aFutureOr<T?>.dynamic,void,Nulland a type parameter are not judged. - Every
returnof the body returns the literalnullor nothing. An expression body is the literalnull.
It does not report a declaration where the null is the point:
- an override, found by the member it overrides, not by the annotation;
- an instance member of a mixin, of a class that another library may extend, or of a
finalclass that a class of its library extends or implements: a default that a subclass replaces; - a function or a method that the file names other than in a call: a callback whose type asks for a result that may be null;
- a body that holds a
TODOor aFIXMEcomment: a placeholder.
A function that only another file tears off, such as a validator that always passes, is reported.
A nullable result that is always null makes every caller write a branch that never runs. It also hides that the value it was meant to give was never written.
The rule is in strict only: a hook that returns null on purpose is common enough that recommended would be loud.
Example
Section titled “Example”String? displayNameOf(User user) { if (user.isGuest) return null; return null;}String? displayNameOf(User user) { if (user.isGuest) return null; return user.name;}Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// Kept for the interface the generated code calls.// ignore: assay/always_returns_null// ignore_for_file: assay/always_returns_null silences it in a whole file, and // ignore: always_returns_null without the prefix works too. See Suppressions.