I want to be able to construct an object from inside a generic function. I tried the following:
abstract class Interface
{
Interface.func(int x);
}
class Test implements Interface
{
Test.func(int x){}
}
T make<T extends Interface>(int x)
{
// the next line doesn't work
return T.func(x);
}
However, this doesn't work. And I get the following error message: The method 'func' isn't defined for the class 'Type'
.
Note: I cannot use mirrors because I'm using dart with flutter.
Factory Constructor in Dart/Flutter We can use the factory keyword for a constructor that return an object instead of creating a new instance. class Customer { String name; int age; String location; static final Customer origin = Customer("", 0, ""); // factory constructor factory Customer.
Dart supports the use of generic types (often denoted as T ) in three general places: In a function's arguments. In local variables inside a function. In a function's return type.
A constructor can be made private by using (_) underscore operator which means private in dart. The same theory applied while extending class also, It's also impossible to call the private constructor if it declares in a separate file.
Named constructors in DartGiving your constructors different names allows your class to have many constructors and also to better represent their use cases outside of the class. The constructor withoutABS initializes the instance variable hasABS to false, before the constructor body executes.
Dart does not support instantiating from a generic type parameter. It doesn't matter if you want to use a named or default constructor (T()
also does not work).
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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With