avoid_late
Reports a late variable with no initializer. Give it a value at the declaration or in the constructor, or make it nullable.
- Tier
- advisory
- Scope
- Dart
- Fix
- none
What it reports
Section titled “What it reports”A late variable with no initializer: a top-level variable, a field, static or not, or a local variable. Each of these three is reported:
late int counter;
class Session { late String token;
static late Session current;}- A
late finalvariable with no initializer is reported too, whileallow_finalisfalse(the default). - Each variable of one declaration is a violation of its own, at its name:
late int first, second = 2, third;has two, atfirstand atthird. - Where nothing in its library assigns a private field, the message says so: its first read throws.
It does not report:
- a
latevariable with an initializer,late final config = loadConfig();. That is lazy initialization: the value is computed on the first read; - a field of a Flutter
Statethat its owninitStatealways assigns, as Flutter documents (see A field thatinitStateassigns); - anything in the test directories, under the presets
recommendedandstrict.
late moves a check from compile time to run time. Without it, the compiler proves that a non-nullable variable has a value before it is read; with it, a read before the first assignment throws a LateInitializationError, only on the path that reads too early, which may be one no test takes. It makes the error “non-nullable field must be initialized” go away without deciding when the value exists. The rule is advisory because late without an initializer has sound uses, such as a field that a framework callback sets before anything reads it.
Example
Section titled “Example”class ProfileScreen { late User user;
Future<void> open(String id) async { user = await loadUser(id); }
String get title => user.name;}title throws when it is read before open has finished.
class ProfileScreen { ProfileScreen(this.user);
final User user;
String get title => user.name;}Or, where the value really arrives later, by saying so in the type:
class ProfileScreen { User? user;
String get title => user?.name ?? 'Loading';}A value that is costly to compute and not always needed keeps late, with its initializer: late final index = buildIndex();.
Rule parameters
Section titled “Rule parameters”Set under the assay: key of the project’s root analysis_options.yaml.
| Rule parameter | Default | Effect |
|---|---|---|
allow_final |
false |
true allows a late final variable with no initializer. false reports it like any other. |
enabled |
true |
false switches the rule off for the whole project. |
exclude |
[] |
Path globs where the rule is silent. |
assay: rules: avoid_late: allow_final: trueSuppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// didChangeDependencies runs before build, which is the first reader.// ignore: assay/avoid_late// ignore_for_file: assay/avoid_late silences it in a whole file, and // ignore: avoid_late without the prefix works too. See Suppressions.
Details
Section titled “Details”All cases
What it reports, in full
Section titled “What it reports, in full”It does not report a variable that is not late, or the word in a name, a string or a comment. A late variable with an initializer cannot be read before it has a value.
A late variable without an initializer is reported even where every path assigns it before it is read, such as a field that every constructor body sets or a local variable assigned on both branches of an if. A local variable needs no late there, and for a field the constructor’s initializer list does the same without it.
Where nothing in its library (its parts and generated parts included) assigns a private field, the message says so: its first read throws. If such a field, or such a private top-level variable, is also read, the blocking rule late_field_never_assigned reports it instead, so the place has one violation, not two. Where that rule does not judge the file (enabled: false, or its own exclude), this rule reports it, with the same message.
A field that initState assigns
Section titled “A field that initState assigns”Flutter calls initState once, before build, didChangeDependencies or anything else of the state runs. So a field that initState always assigns has its value before any reader, and Flutter documents late for exactly this:
class _CodeFormState extends State<CodeForm> { late final GlobalKey<FormState> _formKey; late final TextEditingController _codeController;
@override void initState() { super.initState(); _formKey = GlobalKey<FormState>(); _codeController = TextEditingController()..addListener(_changed); }Neither field is reported. The exemption holds when all of these are true:
- The class is a Flutter
State, the framework’s class frompackage:flutter, extended directly or through a base class or a mixin of the project. A class of the project namedState, or a plain Dart class with aninitStatemethod, does not count. - The field is an instance field of that class itself,
lateorlate final. A static field, a top-level variable and a field that a base class declares are reported. - The class’s own
initStateassigns the field with=, by its bare name or onthis(_f = …;,this._f = …;, also_f = Foo()..bar();and_a = _b = …;), as a statement directly in its body. Wheresuper.initState()is called, and how often the field is assigned, do not matter. - No statement before that assignment can return, such as
if (!mounted) return;, andinitStateis notasync.
A field assigned any other way is reported: inside an if, a loop, a switch, a try or a block of its own; in a closure or a local function, even one that initState calls at once; with ??= or a compound operator; in a method that initState calls; or only in didChangeDependencies, build or a callback. So is a field that a mixin on State declares and assigns in its own initState.
Rule parameter fine print
Section titled “Rule parameter fine print”A late final variable with no initializer can be assigned only once: a second assignment throws. It can still be read too early, so it is reported by default. With allow_final: true, late int counter; is reported and late final int limit; is not. Only the keyword final counts.