prefer_getter_over_method
v1.0.0 Warning Code Quality
This rule flags a no-argument method whose body only reads a value, where a getter reads as the property it is.
Why use this rule
Section titled “Why use this rule”order.getTotal() and order.total return the same thing, but only the second reads as a property of the order. Effective Dart’s rule is that a member doing no real work and taking no arguments should be a getter; the empty parentheses otherwise suggest something happens when you call it.
This rule is in the pedantic preset, because where the line falls between “a property” and “a call” is a genuine API-design judgement.
See also: Effective Dart: prefer a getter
What is never reported
Section titled “What is never reported”The empirical run against a production codebase turned up three classes of member that must keep their parentheses, and all three are excluded:
- A body that calls anything.
Clock.now()andsixDigitCode()answer differently on each call, and a getter promises a stable property. Only a body built from field reads and operators qualifies. - A conventional name.
toJsonis what every serialiser looks for,callis the invocation operator in all but name, andcopyWith/toListare established shapes a reader expects invoked. - A
StreamorFuturereturn. A stream is something you subscribe to, not a property you read, sowatchUser()keeps its parentheses.
Also skipped: a void method (called for an effect), an @override (which must keep the supertype’s shape), a generic method (a getter cannot take type arguments), and a block body, which may be doing the work the parentheses promise.
class Order { final int amount;
int total() => amount * 2;}class Order { final int amount;
int get total => amount * 2;}Enabling this rule
Section titled “Enabling this rule”This rule is in the pedantic preset, so it is enabled by preset: pedantic or by name:
rules: prefer_getter_over_method: enabled: trueTurning this rule off
Section titled “Turning this rule off”To disable this rule:
rules: prefer_getter_over_method: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”match_getter_setter_field_names— Make a getter and setter pair use the same field.avoid_accessing_other_classes_private_members— Make the underscore mean what everyone reads it as.avoid_commented_out_code— Detect and flag commented-out code.avoid_complex_conditions— Keep boolean conditions within an operand budget.