avoid_accessing_other_classes_private_members
This rule flags one class reading another class’s private member.
This rule is in the pedantic preset: it imposes an architecture rather than catching a defect.
Why use this rule
Section titled “Why use this rule”Dart scopes privacy to the library, not the class. _field is visible to every declaration in the same file — and to every part of it. Most people write _ meaning “mine”, and the language quietly means “this file’s”.
In a short file those coincide. In a long one, or a part-heavy library, they do not, and a class ends up depending on another’s internals with nothing in the code to mark it. This rule makes the language behave the way the underscore already reads.
Several idioms legitimately reach across, and are exempt:
- A
Statereadingwidget._foo— one object the framework split in two. copyWith,operator ==,hashCodeandtoString, which exist precisely to read another instance’s fields.- Another instance of the same class:
other._valueinside==is the pattern, not a violation. this._xand a bare_x, which are the class’s own business.
See also: Dart: libraries and privacy
class Account { int _balance = 0;}
class Report { // Compiles, because both classes live in one library. int total(Account account) => account._balance;}class Account { int _balance = 0;
int get balance => _balance;
// Another instance of the SAME class is the `==` / `copyWith` pattern. bool sameAs(Account other) => _balance == other._balance;}
class Report { int total(Account account) => account.balance;}Options
Section titled “Options”many_lints: rules: avoid_accessing_other_classes_private_members: additional_ignored_members: [merge]rules: avoid_accessing_other_classes_private_members: additional_ignored_members: [merge]| Option | Type | Default | Description |
|---|---|---|---|
ignored_members |
list of strings | [copyWith, ==, hashCode, toString] |
Members whose job is to read another instance’s fields |
additional_ignored_members |
list of strings | [] |
Names to add to that list |
Turning this rule off
Section titled “Turning this rule off”To disable this rule:
rules: avoid_accessing_other_classes_private_members: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”prefer_private_named_parameters— Prefer private named parameters (Dart 3.12+) over initializer-list boilerplate.prefer_widget_private_members— A widget’s public API is its constructor.avoid_commented_out_code— Detect and flag commented-out code.avoid_complex_conditions— Keep boolean conditions within an operand budget.