2

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)

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Muhammad Talha
  • 165
  • 1
  • 8

3 Answers3

1

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>();
eamirho3ein
  • 16,619
  • 2
  • 12
  • 23
  • Your answer was pretty close. The only thing missing was extending T like ```class CustomWidget extends StatelessWidget```. Moreover, adding this, removes the need of creating a parameter of type T. – Muhammad Talha Nov 20 '22 at 19:02
  • Yes that could be too, I will update my answer with that. – eamirho3ein Nov 20 '22 at 19:03
0

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){
      
    }
  }
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
0

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
Gwhyyy
  • 7,554
  • 3
  • 8
  • 35