Why can't dynamically-typed function in Flutter return the correct type?

Viewed 910

I have this function:

U on<T, U> (T value, T defaultValue, U Function (T value) builder) => builder(value ?? defaultValue);

If I use it like this:

var a = "Hello";
var b = "World";
final result = on(a, b, (value) => Text(value))

Inside the builder callback parameter, the value type is always dynamic. Why it can't have the same type as the parameter a and b?

1 Answers

Dart currently does not support inference in parameter lists. This issue is being tracked however #731.

Right now you would need to explicitly type this:

final result = on(a, b, (String value) => Text(value))

This at least enforces, that a b and the builder share the same type.

With the upcoming implicit-dynamic analyzer rule, things like these will get spotted more easly and the increased maintance overhead hopefully lets the dart language maintainers reconsider the prioritization of the inference issue.

Related