Skip to content

prefer_shorthands_with_static_fields

v0.3.0 Warning Fix Shorthand Patterns

This rule flags Currency.usd where the expected type is already Currency, because .usd says the same thing.

It applies wherever the context supplies the type: switch cases and switch expression patterns, typed variable declarations, == comparisons, default parameter values, and returns from a function with a declared return type.

Enums have their own rule — prefer_shorthands_with_enums. This one is for value classes with static const instances.

See also: Dart language — dot shorthands

class Currency {
const Currency(this.code);
final String code;
static const usd = Currency('USD');
static const eur = Currency('EUR');
}
void example(Currency? selected) {
switch (selected) {
case Currency.usd: // LINT
print('dollars');
default:
break;
}
final Currency fallback = Currency.eur; // LINT
if (selected == Currency.usd) {} // LINT
}
void example(Currency? selected) {
switch (selected) {
case .usd:
print('dollars');
default:
break;
}
final Currency fallback = .eur;
if (selected == .usd) {}
}
// Don't
void price(double amount, {Currency in_ = Currency.usd}) {}
// Do
void price(double amount, {Currency in_ = .usd}) {}

Both the arrow body and an explicit return are reported:

// Don't
Currency preferred() => Currency.usd;
Currency preferredOrDefault(Currency? chosen) {
return chosen ?? Currency.eur;
}
// Do
Currency preferred() => .usd;
Currency preferredOrDefault(Currency? chosen) {
return chosen ?? .eur;
}
// Don't
final symbol = switch (selected) {
Currency.usd => r'$',
Currency.eur => '€',
_ => '?',
};
// Do
final symbol = switch (selected) {
.usd => r'$',
.eur => '€',
_ => '?',
};

Keeping the class name is correct — and the rule stays silent — when the shorthand would not compile or would mean something else:

No context type. Object getObject() => Currency.usd; is not reported: the expected type is Object, so .usd has nothing to resolve against.

The field’s type differs from its class. static const String staticString = 'test' on Currency is a String, not a Currency, so Currency.staticString is left alone.

Access through an import prefix. prefix.Currency.usd is skipped, since the leading name is the library prefix rather than the class.

A generic type argument inferred from the argument. In Box(items: const [Currency.usd]) the analyzer solves T from the element, so there is no downward context and .usd would fail to compile. Writing Box<Currency>(items: const [.usd]) gives a real context type and is reported.

This rule is in the opinionated preset, so it is on with preset: opinionated, or by name:

many_lints.yaml
rules:
prefer_shorthands_with_static_fields: true

To turn it off again:

many_lints.yaml
rules:
prefer_shorthands_with_static_fields: false

To keep the rule on but skip certain paths, use per-rule exclude.