본문 바로가기

Flutter/07 State - Getx

[Flutter] Getx - GetxService

이번 카테고리는 GetX 의 GetxService 에 대해서 알아보겠습니다.

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

소스코드 위치 - Release 13_getx_service · mike-bskim/getx_test · GitHub

 

Release 13_getx_service · mike-bskim/getx_test

 

github.com

 

 

이번 카테고리는 GetX 의 GetxService 에 대해서 알아보겠습니다.

주요 차이점은 GetxController 는 해당 인스턴스가 자동으로 생성/삭제/종료되지만 GetxService 는 생성은 자동으로 되지만 삭제/종료는 수동으로 호출해 주어야 한다.

실제 출력된 로그는 블로그 마지막을 참고하세요

 

프로젝트 구조

/src/home.dart

/src/pages/getx_service/getx_service_page.dart

/src/pages/getx_service/getx_controller_widget.dart

/src/pages/getx_service/getx_service_widget.dart

/src/controller/getx_controller_controller.dart

/src/controller/getx_service_controller.dart

 

/src/home.dart - 추가된 부분은 아래와 같음

 

ElevatedButton(
  style: elevatedButtonStyle,
  child: const Text("GetX Service 예시"),
  onPressed: () {
    Get.to(()=> const GetXServicePage());
  },
),

 

/src/pages/getx_service/getx_service_page.dart

 

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

import '../../controller/getx_controller_controller.dart';
import '../../controller/getx_service_controller.dart';
import 'getx_controller_widget.dart';
import 'getx_service_widget.dart';

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

  @override
  Widget build(BuildContext context) {
    ButtonStyle elevatedButtonStyle =
    ElevatedButton.styleFrom(minimumSize: const Size(200.0, 35.0));

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('GetX Service 예시'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("GetX Controller"),
              onPressed: () {
                Get.to(
                  () => const GetXControllerWidget(),
                  binding: BindingsBuilder(
                    () => Get.lazyPut<GetXControllerController>(
                        () => GetXControllerController()),
                  ),
                );
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("GetX Service"),
              onPressed: () {
                Get.to(
                  () => const GetXServiceWidget(),
                  binding: BindingsBuilder(() {
                    // Get.put(GetXServiceTest());
                    Get.lazyPut<GetXServiceController>(() => GetXServiceController());
                  }),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

 

/src/pages/getx_service/getx_controller_widget.dart

 

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

import '../../controller/getx_controller_controller.dart';

class GetXControllerWidget extends GetView<GetXControllerController> {
  const GetXControllerWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ButtonStyle elevatedButtonStyle =
    ElevatedButton.styleFrom(minimumSize: const Size(200.0, 35.0));
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('GetX Controller'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(
              () => Text(
                controller.count.value.toString(),
                style: const TextStyle(fontSize: 50),
              ),
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("GetX Controller Increase"),
              onPressed: () {
                controller.increase();
                debugPrint('hashCode[${controller.hashCode}] : ${controller.count.value}');
              },
            ),
          ],
        ),
      ),
    );
  }
}

 

/src/pages/getx_service/getx_service_widget.dart

 

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

import '../../controller/getx_service_controller.dart';

class GetXServiceWidget extends GetView<GetXServiceController> {
  const GetXServiceWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ButtonStyle elevatedButtonStyle =
        ElevatedButton.styleFrom(minimumSize: const Size(200.0, 35.0));

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('GetX Service'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(
              () => Text(
                controller.count.value.toString(),
                style: const TextStyle(fontSize: 50),
              ),
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("GetX Service Increase"),
              onPressed: () {
                controller.increase();
                debugPrint('hashCode[${controller.hashCode}] : ${controller.count.value}');
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("GetX Service clear"),
              onPressed: () {
                Get.delete<GetXServiceController>(force: true);
                Get.back();
              },
            ),
          ],
        ),
      ),
    );
  }
}

 

/src/controller/getx_controller_controller.dart - 호출된 화면이 종료되면 인스턴스도 같이 종료

 

import 'package:get/get.dart';

class GetXControllerController extends GetxController {
  static GetXControllerController get to => Get.find();
  RxInt count = 0.obs;

  void increase() {
    count++;
  }
}

 

// 첫번째 클릭
[GETX] GOING TO ROUTE /GetXControllerWidget
[GETX] Instance "GetXControllerController" has been created
[GETX] Instance "GetXControllerController" has been initialized
I/flutter ( 5617): hashCode[302361159] : 1
I/flutter ( 5617): hashCode[302361159] : 2
[GETX] CLOSE TO ROUTE /GetXControllerWidget
[GETX] "GetXControllerController" onDelete() called
[GETX] "GetXControllerController" deleted from memory
// 두번재 클릭 - count 가 자동 초기화 됨
[GETX] GOING TO ROUTE /GetXControllerWidget
[GETX] Instance "GetXControllerController" has been created
[GETX] Instance "GetXControllerController" has been initialized
I/flutter ( 5617): hashCode[450462405] : 1
I/flutter ( 5617): hashCode[450462405] : 2
[GETX] CLOSE TO ROUTE /GetXControllerWidget
[GETX] "GetXControllerController" onDelete() called
[GETX] "GetXControllerController" deleted from memory

 

 

/src/controller/getx_service_controller.dart - 호출된 화면이 종료되어도 인스턴스가 종료되지 않음

 

import 'package:get/get.dart';

class GetXServiceController extends GetxService {
  static GetXServiceController get to => Get.find();
  RxInt count = 0.obs;

  void increase() {
    count++;
  }
}

 

// 첫번째 클릭
[GETX] GOING TO ROUTE /GetXServiceWidget
[GETX] Instance "GetXServiceController" has been created
[GETX] Instance "GetXServiceController" has been initialized
I/flutter ( 5617): hashCode[122300347] : 1
I/flutter ( 5617): hashCode[122300347] : 2
[GETX] CLOSE TO ROUTE /GetXServiceWidget
// 두번재 클릭 - count 가 유지되는걸 볼수 있다
[GETX] GOING TO ROUTE /GetXServiceWidget
I/flutter ( 5617): hashCode[122300347] : 3
I/flutter ( 5617): hashCode[122300347] : 4
[GETX] CLOSE TO ROUTE /GetXServiceWidget
// 세번째 클릭 - 
[GETX] GOING TO ROUTE /GetXServiceWidget
// clear 버튼 클릭, 인스턴스가 삭제됨
[GETX] "GetXServiceController" onDelete() called
[GETX] "GetXServiceController" deleted from memory
[GETX] CLOSE TO ROUTE /GetXServiceWidget
// count 가 초기화된걸 볼수 있다
[GETX] GOING TO ROUTE /GetXServiceWidget
[GETX] Instance "GetXServiceController" has been created
[GETX] Instance "GetXServiceController" has been initialized
I/flutter ( 5617): hashCode[525228681] : 1
I/flutter ( 5617): hashCode[525228681] : 2

 

 

 

 

 

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