Skip to main content

prefer_final_parameters

Learn about the prefer_final_parameters linter rule.

Deprecated
Fix available

Prefer final for parameter declarations if they are not reassigned.

Details

#

Note: This lint rule was deprecated in Dart 3.11 and is set to be removed in a future release of the Dart SDK. Also note that the lint is not applied to code that is opted in to the primary-constructors language feature where using final for a parameter becomes a compile-time error. If you want to ensure parameters aren't reassigned in function bodies, consider enabling the parameter_assignments lint rule instead.

DO prefer declaring parameters as final if they are not reassigned in the function body.

Declaring parameters as final when possible is a good practice because it helps avoid accidental reassignments.

BAD:

dart
void badParameter(String label) { // LINT  print(label); } 

GOOD:

dart
void goodParameter(final String label) { // OK  print(label); } 

BAD:

dart
void badExpression(int value) => print(value); // LINT 

GOOD:

dart
void goodExpression(final int value) => print(value); // OK 

BAD:

dart
[1, 4, 6, 8].forEach((value) => print(value + 2)); // LINT 

GOOD:

dart
[1, 4, 6, 8].forEach((final value) => print(value + 2)); // OK 

GOOD:

dart
void mutableParameter(String label) { // OK  print(label);  label = 'Hello Linter!';  print(label); } 

Incompatible rules

#

The prefer_final_parameters lint is incompatible with the following rules:

Enable

#

To enable the prefer_final_parameters rule, add prefer_final_parameters under linter > rules in your analysis_options.yaml file:

analysis_options.yaml
yaml
linter:  rules:  - prefer_final_parameters 

If you're instead using the YAML map syntax to configure linter rules, add prefer_final_parameters: true under linter > rules:

analysis_options.yaml
yaml
linter:  rules:  prefer_final_parameters: true