본문 바로가기

Flutter/07 State - Getx

[Flutter] GetX - State management(reactive)

이번 카테고리는 GetX 의 state management(reactive) 에 대해서 알아보겠습니다.

개발환경 : 윈도우11, 안드로이드 스튜디오, flutter 3.0.1

소스코드 위치 - Release 10_getx_state_menagement_reactive · mike-bskim/getx_test · GitHub

 

Release 10_getx_state_menagement_reactive · mike-bskim/getx_test

 

github.com

 

 

프로젝트 구조

/src/home.dart

/src/controller/reactive_state_controller.dart

/src/pages/reactive_state_manage/reactive_state_manage_page.dart

 

/src/home.dart

 

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'pages/argument/argument_page.dart';
import 'pages/normal/first.dart';
import 'pages/reactive_state_manage/reactive_state_manage_page.dart';
import 'pages/simple_state_manage/simple_state_manage_page.dart';

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ButtonStyle elevatedButtonStyle =
        ElevatedButton.styleFrom(minimumSize: const Size(280.0, 35.0));
    Divider divider = const Divider(
        height: 8, thickness: 1, indent: 16, endIndent: 16, color: Colors.grey);

    return Scaffold(
      appBar: AppBar(
        title: const Text("라우트 관리 홈"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("단순 페이지 라우팅"),
              onPressed: () {
                // Navigator.of(context).push(MaterialPageRoute(
                //   builder: (BuildContext context) => const FirstPage(),
                // ));
                Get.to(() => const FirstPage());
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("named 페이지 라우팅"),
              onPressed: () {
                // Navigator.of(context).pushNamed("/first-named");
                Get.toNamed("first-named");
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("Arguments 로 데이터 보내기 : Flutter"),
              onPressed: () {
                // 문자열, 숫자 전달 가능
                // Get.to(const ArgumentPage(), arguments: "Flutter");
                // Get.to(() => const ArgumentPage(), arguments: 5);
                // map 타입 전달
                // Get.to(() => const ArgumentPage(), arguments: {"name": "Flutter", "age": 22});
                // 클래스 객체도 전달가능
                Get.to(() => const ArgumentPage(),
                    arguments: User(name: "Flutter", age: 3.0));
                // Get.toNamed("/argument", arguments: "Flutter");
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("URL Parameters 로 데이터 보내기"),
              onPressed: () {
                Get.toNamed("/user/1424?name=Flutter&age=22");
              },
            ),
            divider,
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("단순 상태관리"),
              onPressed: () {
                Get.to(() => const SimpleStateManagePage());
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("반응형 상태관리"),
              onPressed: () {
                Get.to(() => const ReactiveStateManagePage());
              },
            ),
          ],
        ),
      ),
    );
  }
}

class User {
  final String name;
  final double age;

  User({required this.name, required this.age});
}

 

/src/controller/reactive_state_controller.dart

 

import 'package:get/get.dart';

class User {
  String name;
  int age;

  User({
    required this.name,
    required this.age,
  });

  @override
  String toString() => 'User(name: $name, age: $age)';
}

class ReactiveStateController extends GetxController {
  RxInt count = 0.obs;
  Rx<User> user = User(name: "Flutter", age: 22).obs;
  RxList<dynamic> d = [].obs;

  void increment() {
    count++;
  }

  void init(int number) {
    count(number);
    user.update((u) {
      u?.name = 'Flutter';
    });
    d.clear();
  }

  void updateName(String newName) {
    user.update((u) {
      u?.name = newName;
    });
  }

  void push() {
    d.add("1");
  }

  // @override
  // void onInit() {
  //   ever(count, (_) => debugPrint("매번 호출"));
  //   once(count, (_) => debugPrint("최초 호출"));
  //   debounce(count, (_) => debugPrint("마지막 변경에 한번만 시간차 두고 호출"),
  //       time: const Duration(seconds: 1));
  //   interval(count, (_) => debugPrint("변경되고 있는 동안 1초 간격으로 호출"),
  //       time: const Duration(seconds: 1));
  //   super.onInit();
  // }

}

 

/src/pages/reactive_state_manage/reactive_state_manage_page.dart

 

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../controller/reactive_state_controller.dart';

class ReactiveStateManagePage extends StatelessWidget {
  const ReactiveStateManagePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // Get.put(ReactiveStateController());
    // Get.find<ReactiveStateController>() 대신 reactiveStateCtrl 으로 접근가능 
    ReactiveStateController reactiveStateCtrl =
        Get.put(ReactiveStateController());
    ButtonStyle elevatedButtonStyle =
        ElevatedButton.styleFrom(minimumSize: const Size(150.0, 30.0));
    var textStyle = const TextStyle(fontSize: 20);

    return Scaffold(
      appBar: AppBar(
        title: const Text("반응형 상태 관리"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(
              () {
                debugPrint("Count Update");
                return Column(
                  children: [
                    Text(
                      // "${Get.find<ReactiveStateController>().count}",
                      'count: ${reactiveStateCtrl.count.value}',
                      style: textStyle,
                    ),
                    const SizedBox(height: 10,),
                    // 리스트 접근방법
                    Text(reactiveStateCtrl.d.toString(), style: textStyle),
                    const SizedBox(height: 10,),
                    // 클래스 접근방법
                    Text(reactiveStateCtrl.user.value.name, style: textStyle),
                    const SizedBox(height: 10,),
                    Text(reactiveStateCtrl.user.toString(), style: textStyle),
                    const SizedBox(height: 20,),
                  ],
                );
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: Text("count 증가", style: textStyle),
              onPressed: () {
                // Get.find<ReactiveStateController>().increment();
                reactiveStateCtrl.increment();
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: Text("리스트 추가", style: textStyle),
              onPressed: () {
                // Get.find<ReactiveStateController>().push();
                reactiveStateCtrl.push();
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: Text("이름변경", style: textStyle),
              onPressed: () {
                // Get.find<ReactiveStateController>().updateName('Google');
                reactiveStateCtrl.updateName('Google ${reactiveStateCtrl.count.value}');
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: Text("전체 초기화", style: textStyle),
              onPressed: () {
                // Get.find<ReactiveStateController>().init(0);
                reactiveStateCtrl.init(0);
              },
            ),
          ],
        ),
      ),
    );
  }
}

 

 

 

 

 

[참고자료] 유투브 - 개발하는 남자.

'Flutter > 07 State - Getx' 카테고리의 다른 글

[Flutter] Getx - Binding  (0) 2022.06.07
[Flutter] GetX - Dependency injection  (0) 2022.06.07
[Flutter] GetX - State management(update)  (0) 2022.06.06
[Flutter] GetX (Parameters route)  (1) 2022.06.06
[Flutter] GetX (Arguments route)  (0) 2022.06.06