accessor_reads_other_field
Reports a getter or setter whose field is named for another member of its class, such as int get height => _width;. Point it at its own field.
- Tier
- advisory
- Scope
- Dart
- Lowest preset
- recommended
- Fix
- none
What it reports
Section titled “What it reports”A getter that only reads a field of its class, or a setter that only writes one with its parameter, where the field is named for another member. Names are compared without their leading underscores, so _width is named like width.
The accessor is reported when its field is named otherwise than the accessor, and either:
- the class has another field named like the accessor, which the accessor leaves unused:
get height => _widthwhile_heightexists; - the field is named like another member of the class:
get area => _depthwhiledepthexists.
Only a body that is an arrow, a single return or a single assignment counts, with the field written as x or this.x.
It does not report:
- a field with a name of its own:
List<T> get items => _list;,int get count => _n;; - an accessor that computes its value:
int get length => _list.length;; - a deprecated accessor, which is how an old name is kept for the member that replaces it;
- a variable that is not a field of the class, such as a top-level one.
An alias that is not deprecated, int get w => _width; beside width, is reported. A justified suppression says it is meant.
Accessors come in rows, and you write a row by copying the one above. If you rename the accessor but not the field, height reads _width. The class compiles, and every caller gets the wrong value.
The rule is advisory because an accessor sometimes reads another field on purpose.
Example
Section titled “Example”class Size { Size(this._width, this._height); final int _width; final int _height;
int get width => _width; int get height => _width;}class Size { Size(this._width, this._height); final int _width; final int _height;
int get width => _width; int get height => _height;}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. |
assay: rules: accessor_reads_other_field: exclude: ["lib/generated/**"]Suppressing it
Section titled “Suppressing it”Write why on the line directly above the suppression:
// A square's height is its side; the name stays for the shape interface.// ignore: assay/accessor_reads_other_field// ignore_for_file: assay/accessor_reads_other_field silences it in a whole file, and // ignore: accessor_reads_other_field without the prefix works too. See Suppressions.