본문 바로가기

Flutter/07 State - Getx

[Flutter] GetX - State management(update)

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

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

소스코드 위치 - Release 09_getx_state_menagement_update · mike-bskim/getx_test · GitHub

 

Release 09_getx_state_menagement_update · mike-bskim/getx_test

 

github.com

 

 

프로젝트 구조

/src/home.dart

/src/controller/simple_state_controller.dart

/src/pages/simple_state_manage/with_getx.dart

/src/pages/simple_state_manage/with_provider.dart

/src/pages/simple_state_manage/simple_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/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));

    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");
              },
            ),
            const Divider(
              height: 8,
              thickness: 1,
              indent: 16,
              endIndent: 16,
              color: Colors.grey,
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("단순 상태관리"),
              onPressed: () {
                Get.to(() => const SimpleStateManagePage());
              },
            ),
          ],
        ),
      ),
    );
  }
}

class User {
  final String name;
  final double age;

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

 

/src/controller/simple_state_controller.dart

 

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

class SimpleStateControllerWithGetX extends GetxController {
  int count = 0;
  void increment() {
    count++;
    update();
  }

  void putNumber(int number) {
    count = number;
    update();
  }

  void incrementForId(String id) {
    count++;
    update([id]);
  }
}

class SimpleStateControllerWithProvider extends ChangeNotifier {
  int count = 0;
  void increment() {
    count++;
    notifyListeners();
  }
}

 

/src/pages/simple_state_manage/with_getx.dart

 

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

import '../../controller/simple_state_controller.dart';

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

  @override
  Widget build(BuildContext context) {
    debugPrint('with GetX >> build');
    // injection
    Get.put(SimpleStateControllerWithGetX());

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text("GetX", style: TextStyle(fontSize: 30)),

// 컨트롤러에 접근하는 방법중 하나가 GetBuilder 통해서 접근 가능
          GetBuilder<SimpleStateControllerWithGetX>(
          // id 를 test 로 설정하여 구분가능
            id: "test",
            builder: (controller) {
              debugPrint("counter:${controller.count} + ID is 'test'");
             return Text(
               "${controller.count}",
               style: const TextStyle(fontSize: 50),
             );
            }
          ),
// 컨트롤러에 접근하는 방법중 하나가 GetBuilder 통해서 접근 가능
          GetBuilder<SimpleStateControllerWithGetX>(
          // id 를 설정하지 않아서 구분가능
            builder: (controller) {
              debugPrint("counter:${controller.count} + no ID");
              return Text(
                controller.count.toString(),
                style: const TextStyle(fontSize: 50),
              );
            },
          ),
          ElevatedButton(
            child: const Text("+", style: TextStyle(fontSize: 30)),
            onPressed: () {
              // 컨트롤러에 접근하는 방법중 하나가 Get.find<>() 통해서 접근 가능
              Get.find<SimpleStateControllerWithGetX>().incrementForId("test");
            },
          ),
          ElevatedButton(
            child: const Text("+", style: TextStyle(fontSize: 30)),
            onPressed: () {
              Get.find<SimpleStateControllerWithGetX>().increment();
              // Get.find<SimpleStateControllerWithGetX>().incrementForId("test");
            },
          ),
          // ElevatedButton(
          //   child: const Text("5로 변경", style: TextStyle(fontSize: 30)),
          //   onPressed: () {
          //     Get.find<SimpleStateControllerWithGetX>().putNumber(5);
          //   },
          // ),
        ],
      ),
    );
  }
}

 

/src/pages/simple_state_manage/with_provider.dart

 

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

import '../../controller/simple_state_controller.dart';

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

  // context 로만 표시하면(BuildContext 생략시), Widget _button(context) 하면
  // context 타입이 dynamic 으로 적용되어 context.read() 오류가 발생한다.
  Widget _button(BuildContext context) {
    return ElevatedButton(
      child: const Text("+", style: TextStyle(fontSize: 30)),
      onPressed: () {
        // 아래 2가지 경우로 접근이 가능하다
        // Provider.of<SimpleStateControllerWithProvider>(context, listen: false)
        //     .increment();
        context.read<SimpleStateControllerWithProvider>().increment();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    debugPrint('with provider >> build');
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text("Provider", style: TextStyle(fontSize: 30)),
          Consumer<SimpleStateControllerWithProvider>(
            builder: (_, snapshot, child) {
              return Text(snapshot.count.toString(),
                  style: const TextStyle(fontSize: 50));
            },
          ),
          ElevatedButton(
            child: const Text("+", style: TextStyle(fontSize: 30)),
            onPressed: () {
              // 아래 2가지 경우로 접근이 가능하다
              // Provider.of<SimpleStateControllerWithProvider>(context,
              //     listen: false)
              //     .increment();
              context.read<SimpleStateControllerWithProvider>().increment();
            },
          ),
          _button(context),
        ],
      ),
    );
  }
}

 

/src/pages/simple_state_manage/simple_state_manage_page.dart

 

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

import '../../controller/simple_state_controller.dart';
import 'with_getx.dart';
import 'with_provider.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("단순 상태 관리"),
      ),
      body: Column(
        children: [
          const Expanded(
            child: WithGetX(),
          ),
          Expanded(
            child: ChangeNotifierProvider<SimpleStateControllerWithProvider>(
                create: (context) => SimpleStateControllerWithProvider(),
                child: const WithProvider()),
          ),
        ],
      ),
    );
  }
}

 

 

 

 

 

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