flutter

GetX 추가 정리 - 2023.12.15

이나주니 2023. 12. 15. 09:50
반응형

메소드

Get.isRegistered

flutter 에서 GetX 가 특정 컨트롤러를 사용했는지 확인 가능

if (Get.isRegistered<ParentProfileController>()) { // true인 경우 push 되었다는 뜻
  controller = Get.find<ParentProfileController>();
} else {
  controller = Get.put(ParentProfileController());
}

 

Get.snackbar

제목과 메시지를 설정하면 해당 내용으로 Snackbar를 보여준다. 지속시간(duration), 방향(snackPosition), 배경색(backgroundColor) 등 여러 설정들을 추가할 수 있다.

Get.snackbar('Snackbar', 'Snackbar', snackPosition: SnackPosition.TOP);

 

Get.dialog

Get.defaultDialog()와 달리 기존Dialog 위젯을 가져와서 사용할 수 있다

Get.snackbar('Snackbar', 'Snackbar', snackPosition: SnackPosition.TOP);

상태(State) 관리

간단한 방식 - 내가 주로 사용하는 방식 (simple 방식은 메모리를 적게 사용한다는 장점)

GetxController를 extend하는 Controller 클래스를 선언하고, 초기값을 0으로 설정한 count1 변수를 선언한다.

class Controller extends GetxController {
  var count1 = 0;
}

 

GetBuilder()

GetBuilder을 통해 화면에 count1 변수를 보여준다. 이때 init을 설정하지 않으면 에러가 발생하는 것을 유의하자.

GetBuilder<Controller>(
  init: Controller(),
  builder: (_) => Text(
    'clicks: ${_.count1}',
   ),
)

 

Get.find()

Get.find()을 사용하여 increment1()을 호출하는 버튼을 만들어 텍스트 아래에 배치한다.

TextButton(onPressed: Get.find<Controller>().increment1, child: Text('increment1'))

하지만 리빌드해보면 Get.find<Controller>()에서 에러가 발생할 것이다.

이는 Get.find<Controller>()가 Controller를 찾는 시점이 GetBuilder()의 init에서 Controller를 등록하기 이전이라 그렇다.

호출 시점 이전에 오류원인이 되는 컨트롤러를 get.put 을 통해 넣어준다

 

Get.find() 코드 간략화 Tip

 

controller - static 처리

controller에서 static 전역으로 간단하게 접근할 수 있게 설정

아래처럼 코드 한줄 추가

CountControllerWithGetx class

  static CountControllerWithGetx get to => Get.find();

이제 to로 controller에 간단히 접근할 수 있어요.

위에 실습한 코드와 비교해볼게요.

static 활용 X

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

static 활용 O

  CountControllerWithGetx.to.increase();

 

 

참고 : https://velog.io/@coding_egg/Flutter-GetX-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

반응형