Skip to content

Local shadow causes 'cannot be referenced before it is declared' #3801

Open
@mattrberry

Description

@mattrberry
class C {
  final int f;
  C(this.f);
  void m() {
    print(f);
    final f = this.f;
  }
}
main.dart:10:11: Error: Local variable 'f' can't be referenced before it is declared.
    print(f);
          ^
main.dart:11:11: Context: This is the declaration of the variable 'f'.
    final f = this.f;
          ^

In this example, f is both a local and instance variable. I see this pattern used a lot to perform type checks on the instance variable. While I understand the error message and its value, I feel like it doesn't make much sense when the local just shadows the instance variable of the same name.

The following code produces roughly the same error. I feel like it should also work, but it's a little weaker of an argument

void f(int p) {
  print(p);
  final p = 1;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions