Home > front end >  Sending types as parameters in widgets - Flutter
Sending types as parameters in widgets - Flutter

Time:11-21

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)

CodePudding user response:

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>();

CodePudding user response:

Dont use Widget as custom class, It is already provided by flutter framework.

As for your answer you can do

class MyWidget extends StatelessWidget {
  final Type type; 

  const MyWidget({required this.type});

  @override
  Widget build(BuildContext context) {
    if(type is XWidget){
      
    }
  }
}

CodePudding user response:

You need to extend the GetxController in the type passed as a generic like this:

class Widget<T extends GetxController> extends StatelessWidget {
  const Widget({
    super.key,
  });

  @override
  build(BuildContext context) {
    return GetBuilder<T>(
      builder: (T controller) {
        return const SizedBox();
      },
    );
  }
}

Note: using this way you cant actually create a whole new instance from that type in the init parameter like:

 return GetBuilder<T>(
  init: T(), // you can't
  • Related