본문 바로가기

Flutter/07 State - Getx

[Flutter] GetX - Dependency injection

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

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

소스코드 위치 - Release 11_getx_dependency_injection · mike-bskim/getx_test · GitHub

 

Release 11_getx_dependency_injection · mike-bskim/getx_test

 

github.com

 

 

프로젝트 구조

/src/home.dart

/src/controller/dependency_controller.dart

/src/pages/dependencys/dependency_manage_page.dart

/src/pages/dependencys/get_put.dart

/src/pages/dependencys/get_lazyput.dart

/src/pages/dependencys/get_putasync.dart

/src/pages/dependencys/get_create.dart

 

 

/src/home.dart - 이전 화면에 구분선과 버튼을 추가했습니다.

 

divider,
ElevatedButton(
  style: elevatedButtonStyle,
  child: const Text("종속성 관리"),
  onPressed: () {
    Get.to(() => const DependencyManagePage());
  },
),

 

/src/controller/dependency_controller.dart

 

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

class DependencyController extends GetxController {
  RxInt count=0.obs;
  void increase() {
    count++;
  }
  @override
  void onClose() {
    // 종료시 반환되는 해시코드를 출력
    debugPrint(hashCode.toString());
    super.onClose();
  }
}

 

/src/pages/dependencys/dependency_manage_page.dart

 

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../controller/dependency_controller.dart';
import '../../pages/dependencys/get_lazyput.dart';
import '../../pages/dependencys/get_put.dart';
import '../../pages/dependencys/get_putasync.dart';
import 'get_create.dart';

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

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

    return Scaffold(
      appBar: AppBar(
        title: const Text("종속성 관리"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("Get.put"),
              onPressed: () {
                Get.to(
                  () => const GetPut(),
                  binding: BindingsBuilder(() {
                    // 페이지 이동과 동시에 Controller 인스턴스 생성.
                    Get.put(DependencyController());
                  }),
                );
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("Get.lazyPut"),
              onPressed: () {
                Get.to(
                  () => const GetLazyPut(),
                  binding: BindingsBuilder(() {
                    // Get.find 호출시 Controller 인스턴스 생성.
                    Get.lazyPut<DependencyController>(
                        () => DependencyController());
                  }),
                );
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("Get.putAsync"),
              onPressed: () {
                Get.to(
                  () => const GetPutAsync(),
                  binding: BindingsBuilder(() {
                    // async 이후 Controller 인스턴스 생성.
                    Get.putAsync<DependencyController>(() async {
                      await Future.delayed(const Duration(seconds: 5));
                      return DependencyController();
                    });
                  }),
                );
              },
            ),
            ElevatedButton(
              style: elevatedButtonStyle,
              child: const Text("Get.create"),
              onPressed: () {
                Get.to(
                  () => const GetCreate(),
                  binding: BindingsBuilder(() {
                    // Get.find 호출시 마다 새로운 인스턴스 생성함 
                    // 싱클톤방식이 아니라서 삭제를 수동으로 해줘야 함, 수동삭제는 구현못함
                    Get.create<DependencyController>(
                        () => DependencyController());
                  }),
                );
              },
            )
          ],
        ),
      ),
    );
  }
}

 

/src/pages/dependencys/get_put.dart

 

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

import '../../controller/dependency_controller.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("Get.put"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            debugPrint(Get.find<DependencyController>().hashCode.toString());
          },
          child: const Text('Print hashCode'),
        ),
      ),
    );
  }
}

 

[GETX] GOING TO ROUTE /GetPut
[GETX] Instance "DependencyController" has been created
[GETX] Instance "DependencyController" has been initialized
I/flutter ( 8508): 572098119
I/flutter ( 8508): 572098119
[GETX] CLOSE TO ROUTE /GetPut
I/flutter ( 8508): 572098119
[GETX] "DependencyController" onClose() called
[GETX] "DependencyController" deleted from memory

 

/src/pages/dependencys/get_lazyput.dart

 

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

import '../../controller/dependency_controller.dart';

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

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

    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: const Text("Get.lazyPut"),),
        body: Center(
          child: ElevatedButton(
            style: elevatedButtonStyle,
            child: const Text('Print hashCode'),
            onPressed: () {
              debugPrint(Get.find<DependencyController>().hashCode.toString());
            },
          ),
        ),
    );
  }
}

 

[GETX] GOING TO ROUTE /GetLazyPut
[GETX] Instance "DependencyController" has been created
[GETX] Instance "DependencyController" has been initialized
I/flutter ( 8508): 854178480
I/flutter ( 8508): 854178480
[GETX] CLOSE TO ROUTE /GetLazyPut
I/flutter ( 8508): 854178480
[GETX] "DependencyController" onClose() called
[GETX] "DependencyController" deleted from memory

 

/src/pages/dependencys/get_putasync.dart

 

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

import '../../controller/dependency_controller.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("Get.putAsync"),),
      body: Center(
        child: ElevatedButton(
          child: const Text('Print hashCode'),
          onPressed: () {
            debugPrint(Get.find<DependencyController>().hashCode.toString());
          },
        ),
      ),

    );
  }
}

 

[GETX] GOING TO ROUTE /GetPutAsync
// 5초 이후 인스턴스 생성됨
[GETX] Instance "DependencyController" has been created
[GETX] Instance "DependencyController" has been initialized
I/flutter ( 8508): 3325266
I/flutter ( 8508): 3325266
[GETX] CLOSE TO ROUTE /GetPutAsync
I/flutter ( 8508): 3325266
[GETX] "DependencyController" onClose() called
[GETX] "DependencyController" deleted from memory

 

/src/pages/dependencys/get_create.dart

 

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

import '../../controller/dependency_controller.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('Dependency Test - Get.create'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            ElevatedButton(
                onPressed: () {
                  debugPrint(
                      Get.find<DependencyController>().hashCode.toString());
                },
              child: const Text('Print hashCode')),
// 추가버전, 해당 인스턴스를 모두 삭제하는 방법              
            ElevatedButton(
                style: elevatedButtonStyle,
                onPressed: () {
                  Get.delete<DependencyController>(force: true);
                  Get.back();
                },
                child: const Text('Controller Clear')),
              
          ],
        ),
      ),
    );
  }
}

 

[GETX] GOING TO ROUTE /GetCreate
// 버튼(Get.find)을 클릭할때마다 인스턴스가 생성됨
[GETX] Instance "DependencyController" has been initialized
I/flutter ( 8508): 946681360
// 버튼(Get.find)을 클릭할때마다 인스턴스가 생성됨
I/flutter ( 8508): 379067679
[GETX] Instance "DependencyController" has been initialized
// 버튼(Get.find)을 클릭할때마다 인스턴스가 생성됨
I/flutter ( 8508): 768613683
[GETX] Instance "DependencyController" has been initialized
[GETX] CLOSE TO ROUTE /GetCreate
I/flutter ( 8508): 379067679
I/flutter ( 8508): 946681360
I/flutter ( 8508): 768613683
// Close, delete 호출 안됨

 

버튼('Controller Clear') 추가 후, 출력 로그는 아래와 같다.

 

[GETX] GOING TO ROUTE /GetCreate
I/flutter ( 8401): 966063307
[GETX] Instance "DependencyController" has been initialized
I/flutter ( 8401): 361974277
[GETX] Instance "DependencyController" has been initialized
I/flutter ( 8401): 641697536
[GETX] Instance "DependencyController" has been initialized

// 'Controller Clear' 버튼 클릭시 메모리에서 삭제된다
[GETX] "DependencyController" deleted from memory
[GETX] CLOSE TO ROUTE /GetCreate
// 삭제된 인스턴스의 해시코드가 출력된다
I/flutter ( 8401): 641697536
I/flutter ( 8401): 361974277
I/flutter ( 8401): 966063307

 

 

 

 

 

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

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

[Flutter] Getx - GetxService  (0) 2022.06.08
[Flutter] Getx - Binding  (0) 2022.06.07
[Flutter] GetX - State management(reactive)  (0) 2022.06.07
[Flutter] GetX - State management(update)  (0) 2022.06.06
[Flutter] GetX (Parameters route)  (1) 2022.06.06