Im trying to use a constructor on a generic but since a generic ( represented here with T ) can be anything I'm trying to make T be of type "RedClass". If I then pass a class to represent T that also extends "RedClass" I would be able to use a RedClass constructor on T, right?
abstract class RedClass {
RedClass();
RedClass.fromJson(Map<String, dynamic> json)
}
class BlueClass extends RedClass {
BlueClass();
}
class FinalClass<T extends RedClass> {
// Inside FinalClass I can create a BlueClass from the generic T
final happyBlueClass = T.fromJson(someJson)
}
// When creating the FinalClass i pass a class that also extends RedClass
return FinalClass<BlueClass>()
But trying this the generic T does not seem to get access to any .fromJson() constructor. Any ideas?
Thank you all for the suggestions. I really appreciate it.
My solution for now to make the T of FinalClass as generic as possible I needed to pass the constuctors to FinalClass using a provider earlier in the widget tree.
class FinalClassDataBuilder {
final Type model;
final Function builder;
FinalClassDataBuilder({this.model, this.builder});
}
class FinalClassProvider extends StatelessWidget {
final Widget child;
final List<FinalClassDataBuilder> modelbuilderList;
const FinalClassProvider({Key key, this.child, this.modelbuilderList})
: super(key: key);
@override
Widget build(BuildContext context) {
return Provider<List<FinalClassDataBuilder>>(
create: (_) => [...modelbuilderList],
child: child,
);
}
}
class FinalClass<T> {
...
final List<FinalClassDataBuilder> builders =
Provider.of<List<FinalClassDataBuilder>>(context);
final List<<FinalClassDataBuilder>> result = builders
.where((datamodel) => datamodel.model.toString() == T.toString())
.toList();
}
There is no way to do what you are trying to do directly.
You cannot call static methods on type variables, only on the class/mixin/extension they are actually declared in. Static methods need to be known statically , at compile-time, in order to be called.
If you want to create an instance of the type variable, you need to pass a way to do so to the class. Maybe:
class FinalClass<T extends RedClass> {
final T Function(dynamic) _fromJson;
FinalClass(T Function(dynamic) fromJson) : _fromJson = fromJson;
void someMethod(someJson) {
...
var happyBlueClass = _fromJson(someJson);
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.