-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Incorrect unnecessary_cast from analyzer when cast influences type inference #44411
Comments
There are few ways to fix it: final items = [1, 2, 3].map<Widget>((e) => Text(e.toString())).toList();
items.add(SizedBox()); or alternatively: final items = [
for (var e in [1, 2, 3])
Text(e.toString());
SizedBox(),
]
That's wrong message from the analyzer though. Self contained repro: class A {}
class B extends A {}
class C extends A {}
void main() {
final items = [1, 2, 3].map((e) => B()).toList() as List<A>;
items.add(C());
} Produces |
The context type actually won't reach the relevant location in this case, so type inference proceeds from a blank slate. The syntactic context But I agree that the cast does have an effect: The type of |
Thanks for clarification @eernstg. Yeah, now that I actually run the code I see that it only affects the static type of
Given your explanation it is is clearly "redundant cast", though it might have downstream effects on the inference. |
I suspect that it didn't resolve the problem: The compile-time error was gone, because we're no more trying to add a |
You are right, cast doesn't solve the problem. It only helps with compilation. This is the error I get at runtime: |
This code doesn't work: The argument type 'SizedBox' can't be assigned to the parameter type 'Text'.
Adding a cast
as List<Widget>
solves the problem, but then it asks to remove unnecessary cast.The text was updated successfully, but these errors were encountered: