의존성 주입 (binding)

controller를 인스턴스화 하는 방법 ( 의존성 주입 )

put, lazyput, putasync, create 방법이 있음

binding 방법

특정 페이지 안에서 특정 페이지로 이동할때 바인딩

Get.put

  • 페이지 이동시 create, initialized 되고 페이지에서 나올때 delete()가 실행되며 메모리에서 삭제
RaisedButton(
  child: Text("GetPut"),
  onPressed: () {
    //바인딩 : 페이지로 보내주면서 사용할 컨트롤러를 주입하는 방법
    Get.to(
      GetPut(),
      binding: BindingsBuilder(() {
        Get.put(DependencyController());
        //put방식은 페이지 이동시 controller를 메모리에 올려주고 나올땐 알아서 삭제해줌
      }),
    );
  },
),

Get.lazyPut

  • 버튼을 눌러 페이지 이동했을 당시에는 create, initialized되지 않지만 사용할때 생성됨
  • 나올때는 put과 동일하게 삭제
RaisedButton(
  child: Text("Get.lazyPut"),
  onPressed: () {
    Get.to(
      GetLazyPut(),
      binding: BindingsBuilder(() {
        // controller를 사용할때 메모리에 올려줌
        // 나올땐 삭제
        Get.lazyPut<DependencyController>(
            () => DependencyController());
      }),
    );
  },
),

Get.putAsync

  • 페이지에 접근을 할때 비동기식으로 데이터를 받아오거나 가공처리를 오랫동안하고 나서 컨트롤러를 인스턴스화 할때 사용
RaisedButton(
  child: Text("Get.putAsync"),
  onPressed: () {
    Get.to(
      GetPut(),
      binding: BindingsBuilder(() {
        // 페이지에 접근을 할때 비동기식으로 데이터를 받아오거나 가공처리를 오랫동안하고 나서 컨트롤러를 인스턴스화 할때 사용
        Get.putAsync<DependencyController>(() async {
          // 데이터 처리 후 인스턴스화
          await Future.delayed(Duration(seconds: 5));
          return DependencyController();
        });
      }),
    );
  },
),

Get.create

  • 페이지 이동 할 당시에는 생성 안되지만 사용할때 마다 생성됨
  • 자동으로 삭제되지 않기 때문에 사용 종료때마다 삭제 해줘야함
RaisedButton(
  child: Text("Get.create"),
  onPressed: () {
    // 인스턴스를 여러개 생성
    Get.to(GetPut(), binding: BindingsBuilder(() {
      // 사용할때성 마다 인스턴스 생성
      Get.create<DependencyController>(
          () => DependencyController());
    }));
  },
),

앱이 실행될 때 가장 앞에서 바인딩 설정

  • 라우팅 설정의 GetPage안에서 설정
getPages: [
  GetPage(
    name: '/binding',
    page: () => BindingPage(),
    binding: BindingsBuilder(() {
      Get.put(CountControllerWithGetX());
    }),
  ),
],

Bindings를 implements한 클래스를 만들어서 getPages의 binding에 넣어줄 수 있음

class BindingPageBinding implements Bindings {
  @override
  void dependencies() {
    // TODO: implement dependencies
    Get.put(CountControllerWithGetX());
  }
}
GetPage(
  name: '/binding',
  page: () => BindingPage(),
  binding: BindingPageBinding(),
),

참고

https://www.youtube.com/watch?v=KDTjo-6jFKs 

 

728x90

+ Recent posts