본문 바로가기
Flutter

[Flutter / GetX] binding 사용하기

by hymndaniel 2022. 3. 9.

기능

의존성을 주입하는데 사용. 메모리를 관리할때 객체를 언제 메모리에 로드하고 삭제할 것인지 잘 관리할 수 있게된다.

 

사용방법 1 : initialBinding

GetMaterialApp에는 initialBinding 속성이 있다. 가장 초기에 객체화되어야할 controller가 있다면 유용하다.

객체화할 controller들을 미리 정의한 클래스를 지정하면 된다. 

class InitBinding implements Bindings {
  @override
  void dependencies() {
    Get.put(Controller(), permanent: true);
    Get.put(AppController());
  }
}

 

사용방법2 : GetPage - 라우트 설정시

GetMaterialApp의 getPages 속성으로는 라우팅을 할 때 binding하려는 controller를 지정할 수 있다. 즉, 페이지를 라우트하면서 binding된 controller를 객체화하는 것이다. 이 방법을 사용하면 화면이 빌드될때 메모리에 로드하고, 다른 화면으로 이동하면 메모리에서 삭제시킨다. 이동할 페이지에서는 Get.find() 혹은 GetView를 상속받아 controller를 사용할 수 있을 것이다.

getPages: [
        GetPage(name: "/", page: () => Home()),
        GetPage(
          name: "/Second",
          page: () => SecondPage(),
          binding: BindingsBuilder(
            () => Get.lazyPut<SecondPageController>(
                () => SecondPageController()),
          ),
        ),

 

사용방법3 : Get.to - 페이지 이동시

Get.to(
                  SecondPage(),
                  binding: BindingsBuilder(() {
                    Get.put(SecondPageController());
                  }),
                );

 

참고 출처

728x90