[Flutter] GetX사용하기

kimdocs...📄·2023년 12월 1일
0

flutter

목록 보기
21/30

GetX란?

https://github.com/jonataslaw/getx/blob/master/README.ko-kr.md#Get에-대하여

방법

  • 단순 상태 관리자 - GetBuilder
  • 반응 상태 관리자 - GetX/Obx

특징

  • 상태 관리를 위해 StatefulWidget을 사용하지 않아도 됨
  • 상태 관리를 위해 필요한 것은 controller class 이며 controller class 는 상태 관리 방법에 따라 조금 다르다.

설치

dependencies:
  flutter:
    sdk: flutter
  get:

Simple State Management

: 간단한 상태 관리를 위한 기능

Controller

class Controller extends GetxController {
  int _count = 0;
  int get count => _count;
 
  void increment() {
    _count++;
		update(); // update 메소드를 통해 화면을 리빌드시키는 작업을 해주어야함! 이 작업이 있어야 값의 변화가 화면에 나타난다.
  }
}

: Controller는 상태관리를 위해서는 무조건 GetxController를 상속받아야한다.

Controller 사용하기

  1. 선언

    : Get.put을 통해 Controller를 주입한다.

final Controller controller = Get.put(Controller());
  1. 사용
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  MyApp({super.key});
 
  final controller = Get.put(Controller());
 
  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(),
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          GetBuilder<Controller>(
              builder: (_) => Text(
                    'Current Counter : ${controller.count}',
                    style: const TextStyle(fontSize: 20),
                  )),
          const SizedBox(height: 24),
          ElevatedButton(
              onPressed: () => controller.increment(),
              child: const Text(
                'Increase',
                style: TextStyle(fontSize: 24),
              ))
        ],
      )),
    ));
  }
}

[count 출력]

GetBuilder<Controller>(
  builder: (_) => Text(
    'Current Counter : ${controller.count}',
    style: const TextStyle(fontSize: 20),
    )),

GetBuilder를 사용해서 Text위젯을 불러오고 있다. controller인스턴스의 count변수를 출력하고 있음!!

[count update]

ElevatedButton(
  onPressed: () => controller.increment(),
  child: const Text(
    'Increase',
    style: TextStyle(fontSize: 24),
  ))

controller의 increment() 메소드를 호출하여 값을 증가시킨다.

인스턴스 초기화 생략하기

별도의 인스턴스를 초기화 해주지 않고 , GetBuilder 내부에서 초기화를 해주는 것도 가능하다.

GetBuilder<Controller>(
  init: Controller(),
  builder: (_) => Text(
    'Current Counter : ${Get.find<Controller>().count}',
    style: const TextStyle(fontSize: 20),
    )),
...

ElevatedButton(
  onPressed: () => Get.find<Controller>().increment(),
  child: const Text(
    'Increase',
    style: TextStyle(fontSize: 24),
  ))

Reactive State Management

  1. Model 정의
class Person {
  Person({this.age = 0, this.name = ''});
  int age;
  String name;
}
  1. Controller 클래스 정의
class Controller extends GetxController {
  final person = Person().obs;
 
  void updateInfo() {
    person.update((val) { // 내부적으로 받는 콜백 인스턴스, val
      val?.age++;
      val?.name = 'nx006';
    });
  }
}

obs?

: observable의 약자로, 오브젝트의 변화를 감지하겠다는 의미. GetX는 obs가 붙은 오브젝트들의 변화를 감시한다.

obs가 붙은 객체는 update라는 메소드를 사용할 수 있다.

*이때, update 메소드는 Simple State Management에서 소개한 화면을 리빌드 시키는 update메소드와는 그 의미가 다르다.

update?

: 내부적으로 콜백 인스턴스를 받는데, 이 콜백 인스턴스는 감시하고 있는 person오브젝트가 들어온다.

null값이 들어올 수 있으므로 null체크를 해주어야한다. 이후 인스턴스의 값을 변경해주면 GetX가 update메소드를 통한 변화를 감지하고 화면을 리빌드시킨다.

GetX<Controller>(
  init: Controller(),
  builder: (_) => Text(
    'Name : ${Get.find<Controller>().person().name}',
    style: const TextStyle(
      fontSize: 20, color: Colors.white),
  ))

...

floatingActionButton: FloatingActionButton(
  child: const Icon(Icons.add),
  onPressed: () {
    Get.find<Controller>().updateInfo();
  },
)

전체코드

class PersonalCard extends StatelessWidget {
  const PersonalCard({super.key});
 
  
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            margin: const EdgeInsets.all(20),
            width: double.maxFinite,
            height: 100,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Colors.lightBlue,
            ),
            child: Center(
                child: GetX<Controller>(
                    init: Controller(),
                    builder: (_) => Text(
                          'Name : ${Get.find<Controller>().person().name}',
                          style: const TextStyle(
                              fontSize: 20, color: Colors.white),
                        ))),
          ),
          Container(
            margin: const EdgeInsets.all(20),
            width: double.maxFinite,
            height: 100,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Colors.lightBlue,
            ),
            child: Center(
                child: GetX(
                    init: Controller(),
                    builder: (controller) => Text(
                          'Name: ${Get.find<Controller>().person().age}',
                          style: const TextStyle(
                              fontSize: 20, color: Colors.white),
                        ))),
          ),
        ],
      )),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          Get.find<Controller>().updateInfo();
        },
      ),
    );
  }
}
profile
👩‍🌾 GitHub: ezidayzi / 📂 Contact: ezidayzi@gmail.com

0개의 댓글