I’m trying to separate a widget that contains GetBuilder. I want to send type as parameter to the widget but unfortunately unable to achieve it till now.
What I’m trying to do:
class Widget extends StatelessWidget {
final type; // A class type that extends GetxController
const Widget({required this.type});
@override
Widget build(BuildContext context) {
return GetBuilder<type>(
builder: (controller) {
return const SizedBox();
},
);
}
}
I want to make it reusable in multiple places in my project, but different uses require different Controllers, so the type of the GetBuilder is different for every use. Unfortunately, I’ve never implemented anything like this before, so I’m pretty confused because it is different than normal parameters.
The errors:
The name ‘type’ isn’t a type so it can’t be used as a type argument.
Try correcting the name to an existing type, or defining a type named ‘type’. dart(non_type_as_type_argument)
‘dynamic’ doesn’t conform to the bound ‘GetxController’ of the type parameter ‘T’.
Try using a type that is or is a subclass of ‘GetxController’. dart(type_argument_not_matching_bounds)
3
Answers
Dont use
Widget
as custom class, It is already provided by flutter framework.As for your answer you can do
Try this:
and use it like this:
You need to extend the GetxController in the type passed as a generic like this:
Note: using this way you cant actually create a whole new instance from that type in the
init
parameter like: