Why can't dynamically-typed function in Flutter return the correct type?
815
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.
Author by
Chen Li Yong
Currently, I'm a mainly mobile programmer (iOS, swift / obj-C) which currently lead and work in multiple projects.
Updated on December 08, 2022Comments
-
Chen Li Yong over 1 year
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?
-
Darish about 4 yearsclarification required: why do you assign "Hello" to an integer typed variable? You shoud instead use var a="Hellow";
-
Chen Li Yong about 4 years@Darish fixed. I was using int examples at first, but then switch to string midway to make it easier to supply to Text widget.
-
Darish about 4 yearsevent though the type is dynamic, it would not make any problem for you. You can cast it into actual type, say String for example. What problem are you facing?
-
Admin about 4 years
final result = on<String, Text>(a, b, (value) => Text(value));
will fix the issue -
Chen Li Yong about 4 years@Darish the problem is the typecast fails. (cannot convert dynamic into String, or something like that, which is why I asked this)
-
-
Chen Li Yong about 4 yearsOh okay, I don't know that you can enforce a type for the received value like that. Thanks!