You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classC {
finalint f;
C(this.f);
voidm() {
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
voidf(int p) {
print(p);
final p =1;
}
The text was updated successfully, but these errors were encountered:
Working as currently intended. The scope of final f is the entire block it's part of.
Not all local variables have that property, those introduced by a collection element (for (var x in ...) or if (e case var x) ...) are only in scope in their "body element", but stand-alone variable declarations do.
So this is a request to change the current behavior, which means that a variable declaration's variable will only be in scope after the declaration.
It's not a big change, since it's already not allowed to refer to the variable before that, so it would just mean that any place we currently say that "referencing x is not allowed", we'd just skip that x in lookup and move to the outer scope.
That, or have each variable declaration introduce a new scope that covers the rest of the surrounding block.
(We'd probably still want to disallow declaring the same variable more than once in the same scope, although nothing prevents allowing that, with each introducing a new scope.)
(We'd probably still want to disallow declaring the same variable more than once in the same scope, although nothing prevents allowing that, with each introducing a new scope.)
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
The text was updated successfully, but these errors were encountered: