简体   繁体   中英

Flutter: use 2 classes when using StateMixin in getx controller

I am using getx as a statemanagement on my project. I created a controller and I am using StateMixin on my controller.

class HomeController extends GetxController
    with StateMixin<MyModel, List<MyCompleteModel>> {

As you can see I want to use 2 classes by StateMixin . But it's constructor just accepts one class. Except create a new class that contains both of these classes, Is there any way to fix this problem?

Yes you can! And as you guessed it, by inheritance.

At first create a generic State class containing the types you want:

class MyState<T1, T2> { // you can use more like T3, T4...
      T1? state1;
      T2? state2;

      MyState({this.state1, this.state2});
}

Then create a base controller of your own:

abstract class BaseController<T1, T2> extends GetxController with StateMixin<MyState<T1, T2>> {

}

Then extend this base controller:

class HomeController extends BaseController<int, String> {
      @override
      void onInit() {
         super.onInit();

         change(null, status: RxStatus.loading());

         Future.delayed(Duration(seconds: 3), () {
            change(MyState(state1:1,state2: "state2"), status:RxStatus.success());
    });
  }
}

Then on your widget:

controller.obx(
      (state) => Text("${state?.state1} - ${state?.state2}"),
    )

Yes you can by using tuple package. https://pub.dev/packages/tuple

class HomeController extends GetxController
    with StateMixin<Tuple2<MyModel, List<MyCompleteModel>>> {
  @override
  Future<void> onInit() async {
    change(Tuple2(MyModel(), [MyCompleteModel()]), status: RxStatus.success());
  }
}
class HomeView extends StatelessWidget {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(HomeController());
    return controller.obx((state) => Column(
      children: [
        Text(state?.item1.toString() ?? ''),
        Text(state?.item2.first.toString() ?? ''),
      ],
    ));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM