The underscore prefix is used in Dart to indicate members and top-level declarations that are private.
The compiler enforces access restrictions so that private elements can only be accessed from within the library in which they are declared.
Because local variables and parameters are only accessible within the scope in which they are declared, and cannot be exposed to other libraries,
the private accessibility scope doesn’t apply to them. Using an underscore prefix for local variables suggests otherwise and can be misleading.
This rule applies to local variables and parameters of:
- top-level functions
- nested functions and lambdas
- class methods
- class constructors
- extension and extension type methods
Exceptions
Unused parameters are typically named __
, ___
, etc. to indicate that they are intentionally unused. This is a common
practice and is not considered a violation of this rule.
Typical examples of this practice arise with lambdas:
List<int> repeat(int value, int times) =>
List<int>.generate(times, (_) => value); // OK
as well as in pattern matches with wildcards:
String rating(double probability) => switch (probability) {
< 1.05 => 'A',
< 20.0 => 'B',
< 50.0 => 'C',
_ => 'D', // OK
};
as well as catch clauses:
try {
// ...
} on Exception catch (_, s) { // OK
print(s);
}