overwritten_before_read
Reports a value given to a local variable that a later statement replaces before anything reads it. Delete the lost write, or read the value first.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- recommended
- Fix
- deletes the lost write where its value runs no code
What it reports
Section titled “What it reports”A write whose value is lost: var label = ''; label = title;. The violation covers the first write: the declaration with its value, or the assignment.
It is reported when:
- both writes are statements of the same block, or the same case of a
switch; - the first is the variable’s declaration with a value, or a plain assignment to it;
- the second is a plain assignment whose value does not read the variable.
And nothing can read the variable unseen between the two:
- it is a local variable, not
late, and no function literal or local function in the function mentions it; - the statements between the writes do not mention it, and hold no
break,continue,return,throworrethrow; - no catch clause or finally block of a
tryaround the writes mentions it.
The fix deletes the lost write where its value is repeatable (a literal, a constant, a local, a final field and the like), so that nothing is lost with it: an assignment with its line, or the value of a declaration. Where the declaration says var, the fix writes the inferred type in its place, when that type and its type arguments are core library classes; otherwise there is no fix.
A lost write is either dead code, or a sign that the code meant to read the value first or to write another variable. Neither the analyzer nor an SDK lint reports a value replaced before it is read.
Example
Section titled “Example”String label(Item item) { var text = item.name; text = item.title; return text;}String label(Item item) { final text = item.title; return text;}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:
// The first value documents the default the server sends.// ignore: overwritten_before_readvar mode = 'light';// ignore_for_file: assay/overwritten_before_read silences it in a whole file, and the prefixed // ignore: assay/overwritten_before_read works too. See Suppressions.