unnecessary_nullable
Reports a nullable parameter to which every call in the project passes a value that cannot be null. Make the parameter non-nullable.
- Kind
- cross-file check
- Tier
- advisory
- Host
- command-line program only (
assay cross-file) - Fix
- none
What it reports
Section titled “What it reports”Four cases, each with its own message:
| Case | Message |
|---|---|
| Never null: every call passes a value that cannot be null | “The parameter factor of the function scale is nullable, but every call in the project passes it a value that cannot be null.” |
Always null: every call passes the literal null or, where the parameter has no default, leaves it out; at least one passes null |
“The parameter reason of the function stop is always null: every call in the project passes it null.” |
| Never passed: every call leaves out an optional parameter, nullable or not | “The optional parameter step of the function advance is never passed: every call in the project leaves it out.” |
| No null returned: the return type is written nullable, but no way out of the body gives null | “The return type of the function title is nullable, but no way out of it gives null.” |
- It judges the parameters of functions, methods and constructors whose type is written with a
?. - A call from anywhere in the project counts: a test, an example, a generated file.
- Where the callers cannot all be seen, nothing is reported: a function used as a value (
onPressed: _save), an override, an entry point, the public API of a publishable package. - The parameters of a
copyWithmethod are never reported.
A ? on a parameter tells every caller that null is fine, and makes the body handle it: a test, a ?? default, or a !. Where no caller passes null, that code is dead weight: the signature misleads, a branch never runs, and a ! hides the one place where a null would be a defect. Agent-written code leaves such parameters behind (a ? added “to be safe”, a helper written before its callers), and no single file shows them: only every call of the project together does.
The check is advisory: a parameter can be nullable on purpose, for a caller still to come.
Example
Section titled “Example”int scale(int? factor) => (factor ?? 1) * 2;
final doubled = scale(2);int scale(int factor) => factor * 2;
final doubled = scale(2);For an optional parameter whose default is null, the message asks you to make it required as well.
Configuration
Section titled “Configuration”Under the assay: key of the project’s root analysis_options.yaml. The check is on under every preset.
| Key | Default | Effect |
|---|---|---|
assay.cross_file.unnecessary_nullable.enabled |
true |
false switches the check off. The short form unnecessary_nullable: false means the same. |
assay.cross_file.unnecessary_nullable.exclude |
[] |
Path globs, read from the project root, where the check places no result. The files are still read, and their calls count. |
assay: cross_file: unnecessary_nullable: exclude: - lib/api/**Running it
Section titled “Running it”assay cross-file # every cross-file checkassay cross-file unnecessary_nullable # this one aloneIt does not run in the editor and is not part of assay check. Its results never fail the gate (see In the gate).
Suppressing it
Section titled “Suppressing it”A suppression comment does not silence a cross-file check. Use the check’s exclude for a file whose signatures are nullable on purpose, or switch the check off.
Details
Section titled “Details”All cases
The cases in full
Section titled “The cases in full”| Case | Placed at | How to fix |
|---|---|---|
| Never null | the parameter’s name | “Make the parameter non-nullable if no caller needs to pass null.” For an optional parameter whose default is null: “Make the parameter required and non-nullable if no caller needs to pass null.” |
| Always null | the parameter’s name | “Remove the parameter and the code for a value of it, unless a caller is meant to pass one.” |
| Never passed | the parameter’s name | With a default: “Remove the parameter and use its default value where it is read, unless a caller is meant to pass it.” Without one: “Remove the parameter, which is always null, and the code for a value of it, unless a caller is meant to pass it.” The parameter may be positional or named. |
| No null returned | the return type | “Make the return type non-nullable if no caller needs to test for null.” The return type is T?, or for an async body Future<T?> or FutureOr<T?>. Private functions and methods are judged as well. |
- A message names a method as
Cart.addand a constructor asCartorCart.sized. - A declaration is reported for one case at most: never passed first, then always null, then never null. Each case keeps the same caution: nothing is reported where the callers cannot all be seen (see What is never reported), and the parameters of a method named
copyWithare left out. - Always null and never passed leave out a super parameter (
{super.key}) and a Flutter widget key ({Key? key}and any subtype of Flutter’sKey): a constructor takes them by convention, whether a call passes one or not. Only a literalnullcounts as null for “always null”; a nullable value that happens to be null is a value. - No null returned. The ways out are the expression of an expression body and the value of every
returnof a block body, outside its closures. Areturn null, or a value that may be null, keeps it silent. A block body must not reach its end, which would give null: one of its statements must always leave (areturn, athrow, arethrow, anifwhose two branches always leave, atrywhose body and catch clauses always leave, or whosefinallydoes). Any other statement, aswitchand awhile (true)among them, is taken to reach the end, and the function is not reported. Not judged: a generator, a getter, a setter, an operator, a function the project does not call or uses as a value (such as a validator handed to a form field), and an override or what it overrides. - The result is a violation with the source
cross_file, the ruleunnecessary_nullableand the advisory tier. Its fingerprint is made of the line it stands on, as a rule’s is, so it stays the same while other lines of the file change.
What it covers
Section titled “What it covers”The parameters, positional or named, required or optional, of:
| Declaration | Named in the message as |
|---|---|
| a top-level function | function (scale) |
| a method, static or not, of a class, mixin, enum, extension or extension type | method (Cart.add) |
| a constructor, named or not, a factory among them | constructor (Cart, Cart.sized) |
whose type is written nullable, with its ?: int? count, void Function()? onDone, T? value, Object? value, a field formal int? this.count, and a super parameter with a written type, int? super.count.
Not covered:
- a parameter whose type is not written:
this.count,super.key, a closure’s parameter; - a type that is nullable without a
?:dynamic, an alias of a nullable type, an unbounded type parameterT; - a getter, a setter and an operator, which are not called with an argument list;
- an abstract or external declaration, since another implementation stands behind it;
- a local function and a closure.
What counts as a call
Section titled “What counts as a call”- Every call the analyzer resolves to the declaration: a function or method call, an extension method, a static method, a constructor call with or without
newandconst, a dot shorthand (.named(…)), asuper(…)orthis(…)initializer, an enum value with arguments, an annotation with arguments, and the implicitcallof an object (counter(1)). - A constructor’s call of its superclass constructor, with the arguments of its
super(…)initializer and its super parameters, also where nosuper(…)is written. A super parameter passes a value of its own type:{super.size}passes what the superclass declares, a nullable value, while{required int super.size}passes a value that cannot be null. - Calls from anywhere in the project: a test, a benchmark, an example, a script, a file in an excluded path, a generated file, a file that
unused_filesreports. The pass reads every Dart file of the project. - The argument’s static type decides, as the analyzer gives it after promotion:
countafterif (count != null)cannot be null; amaybeof typeint?may, and so may the literalnull, adynamicvalue and a value of an unbounded type parameter. - A call that leaves out an optional parameter passes its default. A default that cannot be null (
{int? size = 3}) counts as a value that cannot be null. No default, or= null, counts as null. - A call from inside the function itself counts, but a function that only calls itself has no call in the project, which is
unused_code’s matter. - A platform-dependent import (
import 'io.dart' if (dart.library.js_interop) 'web.dart';) sends the calls to the file the analyzer resolves it to, so a result there holds for that file’s signature: change the other platform’s file with it.
One parameter is judged at a time: making one non-nullable can make the parameter it is handed on to a result of the next run.
What is never reported
Section titled “What is never reported”Wherever the callers of a function cannot all be seen, nothing of it is reported. A parameter is not reported:
- to which any call passes a value that may be null, the literal
nullamong them, nor an optional parameter whose default may be null that any call leaves out; - of a function with no call in the project from outside itself: that is
unused_code’s matter; - of a function used as a value anywhere in the project: a tear-off (
list.map(scale),onPressed: _save,Cart.new,.sized), a function handed toFunction.apply,compute,Isolate.spawnor a platform channel, the implicit tear-off ofcall. Whoever calls the value is not seen. A function named in a documentation comment ([scale]) is not used as a value. - of a constructor another constructor redirects to (
factory Cart.empty() = Cart;), and of a superclass constructor called by a constructor no code declares: the implicit default constructor of a subclass, and the constructors of a class alias (class C = A with M;) or a mixin application; - of a declaration that may be reached from where the pass cannot see, by the rules of
unused_code: an override and what it overrides or stands in for; an entry point (main,testExecutable,plugin); a declaration that@pragma('vm:entry-point')or an annotation of code generation or a framework keeps alive, with every member and constructor of a type it keeps (a@JsonSerializableor@freezedclass, an@injectableservice, a@RoutePagepage); a member named like a member ofObject,call,toJsonandfromJson; a declaration whose name is used without an element anywhere (called on adynamicvalue, unresolved in a file that does not compile, in a symbol literal), and a constructor whose type’s name is; - of the public API of a package that has one (see below): its callers outside the project are not seen;
- that carries an annotation of code generation or of a framework itself;
- in a file that is not judged, a file that
unused_filesreports, a file that only a condition of an import or an export names, and an excluded path (see Where no result is placed).
A function that code outside Dart calls without an annotation is judged like any other: a method JavaScript calls on an object made with createJSInteropWrapper, a function native code looks up by name, a member found through dart:mirrors. Keep it with @pragma('vm:entry-point'), or use the check’s exclude.
The two package types
Section titled “The two package types”As for unused_code and unused_files, a file’s package is the nearest directory above it, inside the project, that holds a pubspec.yaml. See The two package types.
| Package | What is left out as public API |
|---|---|
marked publish_to: none (an application, an internal package) |
nothing: every call is in the project, so every parameter is judged |
publishable: any other publish_to, or no publish_to line at all |
the parameters of every declaration a public library exports, its own public declarations among them; of every declaration a library of lib/src/ exports from other libraries; of every public member and public constructor of a public type |
the project root’s package, when its pubspec says resolution: workspace |
as a publishable package. Judge the workspace from its root to have the other members’ calls seen. |
| a directory with no pubspec | nothing |
So in a publishable package the check judges private functions and methods, the members of private types, the top-level declarations of lib/src/ that no library exports, and everything in test/, bin/, tool/ and the other directories outside lib/.
A publish_to: none package that other projects use by a path dependency, and a library of lib/src/ that other packages import directly while no library of its package exports it, are judged by these rules too. Judge such a monorepo as a pub workspace from its root, or use the check’s exclude.
Where a pubspec cannot be read, no cross-file check judges that package’s files in that run (see A pubspec that cannot be read).
Where no result is placed
Section titled “Where no result is placed”- In a file that
assay.excludeoranalyzer.excludecovers (with the defaultassay.exclude, no generated file). Such a file is still read, and its calls count. - In a file whose first comment says a generator wrote it, such as
// GENERATED CODE - DO NOT MODIFY BY HAND,DO NOT EDITor@generated. Its calls count. - In a file that the check’s own
excludecovers. - In a directory that holds no source of the project:
.dart_tool, a directory directly under the project root whose name starts with a dot, and the otherscheckleaves out. - In a file that is not judged.
In the gate and the baseline
Section titled “In the gate and the baseline”The gate runs the check with the other cross-file checks: its results never fail the gate, and they pass through the baseline (see In the gate). In a project that already has a baseline, new results enter as news of the cross-file part: record them with baseline update --add, or fix them.
No fix
Section titled “No fix”No fix exists, and none is planned: dropping the ? mechanically is not a fix. The body often tests the parameter for null, falls back with ?? or asserts with !. Once the type is non-nullable, each of those becomes a warning or dead code that a person decides about. An optional parameter whose default is null also needs required or a default. And a caller to come may need the null after all.