Open mat100payette opened 2 years ago
cc @stereotype441 I think this may be an example that would benefit from the extended variant of the function literal heuristic you were exploring, right?
On a related note, yesterday I have also come across a similar inference issue. Please do tell me if it warrants a seperate issue.
Here is some common Flutter code where a typed Future<T>
is initialized and then used in a FutureBuilder<T>
:
Future<int> myFuture = Future.value(1);
FutureBuilder(
future: myFuture,
builder: (_, snapshot) => Text('Is my int even: ${snapshot.data?.isEven}'), // Error
);
This code raises a compile time error since snapshot
is inferred to be an AsyncSnapshot<Object?>
, as opposed to a AsyncSnapshot<int?>
. Obviously, one could fix this error similarly by either doing:
FutureBuilder<int>(...)
or
(_, AsyncSnapshot<int?> snapshot) => ...
both of which aren't DRY.
Just like the chaining issue however, what's unintuitive for new people is that if you hover over FutureBuilder
in the error snippet above, it'll tell you this:
(new) FutureBuilder<int> FutureBuilder({
Key? key,
Future<int>? future,
int? initialData,
required Widget Function(BuildContext, AsyncSnapshot<int>) builder,
})
which shows, here too, that the compiler already should know all the type information based on the usage of myFuture
.
The latter is definitely an instance of https://github.com/dart-lang/language/issues/731 , which @stereotype441 is investigating.
The latter is definitely an instance of #731 , which @stereotype441 is investigating.
Yes ok thank you, I wasn't 100% sure.
Would @stereotype441 mind confirming that the investigation is indeed going to fix this? Kinda left in the dark.
@mat100payette said:
Would @stereotype441 mind confirming that the investigation is indeed going to fix this? Kinda left in the dark.
Yes, I can confirm that the issue you mentioned in https://github.com/dart-lang/language/issues/2037#issuecomment-1000491524 is most definitely the same issue as in #731, which I am working on this quarter.
Here is some function that chains multiple generic functions and returns the result of composing these functions on the caller:
The problem arises when you try to call it with anonymous functions:
In this scenario above, the compiler will know that
foo
is anint
. However, it will not inferString
forbar
; instead, it will inferObject?
, resulting in a compile-time error onint.parse(bar)
.Now, look at these scenarios:
So basically, the information that
bar
should be aString
does exist at compile time; it is simply not conveyed to the type inference. This forces the code to be unnecessarily verbose by always adding the explicit types.