Want to call a named constructor from a generic function in Flutter? There is probably a way to do that on the server, where dart:mirrors (reflection) is available (not tried myself yet), but not in Flutter or the browser.
You would need to maintain a map of types to factory functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
void main() async { final double abc = 1.4; int x = abc.toInt(); print(int.tryParse(abc.toString().split('.')[1])); // int y = abc - x; final t = make<Test>(5); print(t); } abstract class Interface { Interface.func(int x); } class Test implements Interface { Test.func(int x) {} } /// Add factory functions for every Type and every constructor you want to make available to `make` final factories = <Type, Function>{Test: (int x) => Test.func(x)}; T make<T extends Interface>(int x) { return factories[T](x); } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.