controller가 singleton 방식인 것을 활용

기존

controller

class CountControllerWithGetX extends GetxController {
  int count = 0;
  void increase(String id) {
    count++;
    update([id]);
  }
}

contoller에 접근

Get.find<CountControllerWithGetX>().increase();

활용

controller에 state으로 get to 추가

class CountControllerWithGetX extends GetxController {
  static CountControllerWithGetX get to => Get.find();
  int count = 0;
  void increase(String id) {
    count++;
    update([id]);
  }
}

controller.to 로 접근 가능

CountControllerWithGetX.to.increase();

controller가 reactive 방식일때 stateless 대신 getview를 사용해서 접근

stateless -> GetView로 변경

// stateless -> GetView로 변경
class BindingPage extends GetView<CountControllerWithReactive> {
  const BindingPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          Text(
            "GetX",
            style: TextStyle(fontSize: 50),
          ),
                    // reactive 방식이어야함
          Obx(() => Text(
                "${controller.count.value}",
                style: TextStyle(fontSize: 50),
              )),
          RaisedButton(
            onPressed: () {
              //GetView 안에 controller가 있음
              controller.increase();
            },
            child: Text(
              "+",
              style: TextStyle(fontSize: 50),
            ),
          ),
        ],
      ),
    );
  }
}

참고

https://www.youtube.com/watch?v=O1Bw-mwF9xc 

 

728x90

+ Recent posts