skip to Main Content

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


  1. 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){
          
        }
      }
    }
    
    Login or Signup to reply.
  2. 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>();
    
    Login or Signup to reply.
  3. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search