Search code examples
flutterdartflutter-getx

Sending types as parameters in widgets - Flutter


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)


Solution

  • Try this:

    class CustomWidget<T extends GetxController> extends StatelessWidget {
      
      const CustomWidget();
       @override
       Widget build(BuildContext context) {
    
         return GetBuilder<T>(
           builder: (controller) {
              return const SizedBox();
           },
         );
      }
    }
    

    and use it like this:

    CustomWidget<YourCustomType>();