본문 바로가기

Flutter/00 초보때 작성글

[Flutter] Getx with Dependency Injection

아래 내용이 정리가 안된거 같아서 새로 정리한 블로그입니다.

2022.06.07 - [Flutter/07 State - Getx] - [Flutter] GetX - Dependency injection

 

[Flutter] GetX - Dependency injection

이번 카테고리는 GetX 의 dependency injection 에 대해서 알아보겠습니다. 개발환경 : 윈도우11, 안드로이드 스튜디오, flutter 3.0.1 소스코드 위치 - Release 11_getx_dependency_injection · mike-bskim/getx..

unsungit.tistory.com

 

 

 

Getx with Dependency Injection

 

main.dart

 

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'binding_sample.dart';
import 'dependency/controller_manage_page.dart';
import 'getx_simple.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp( // MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: DependencyTestPage(),
    );
  }
}

class DependencyTestPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    print('------------ build(DependencyMainPage) ------------');
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Dependency Test'),
      ),
      body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              DependencyMainPage(),
            ]
        ),
      ),
    );
  }
}

 

controller_manage_page.dart

 

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

import 'get_create.dart';
import 'get_lazyput.dart';
import 'get_put.dart';
import 'get_putasync.dart';


class DependencyUpdateController extends GetxController {
  int count=0;
  void increase() {
    count++;
    update();
  }
}


class DependencyReactiveController extends GetxController {
  RxInt count=0.obs;
  void increase() {
    count++;
  }

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

  @override
  void onInit() { // work 를 설정할수 있음.
    super.onInit();
  }
}


class DependencyMainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          SizedBox(
            width: 130,
            child: ElevatedButton(
              child: Text("Get.put()"),
              onPressed: () {
                Get.to(() => GetPut(),
                  binding: BindingsBuilder(() {
                    Get.put(DependencyUpdateController());
                  }),
                );
              },
            ),
          ),
          SizedBox(
            width: 130,
            child: ElevatedButton(
              child: Text("Get.lazyPut()"),
              onPressed: () {
                Get.to(() => GetLazyPut(),
                  binding: BindingsBuilder(() {
                    Get.lazyPut<DependencyUpdateController>(
                            () => DependencyUpdateController());
                  }),
                );
              },
            ),
          ),
          SizedBox(
            width: 130,
            child: ElevatedButton(
              child: Text("Get.putAsync()"),
              onPressed: () {
                Get.to(() => GetPutAsync(),
                  binding: BindingsBuilder(() {
                    Get.putAsync<DependencyUpdateController>(() async {
                      await Future.delayed(Duration(seconds: 5));
                      return DependencyUpdateController();
                    });
                  }),
                );
              },
            ),
          ),
          SizedBox(
            width: 130,
            child: ElevatedButton(
              child: Text("Get.create()"),
              onPressed: () {
                Get.to(() => GetCreate(),
                  binding: BindingsBuilder(() {
                    Get.create<DependencyReactiveController>(
                            () => DependencyReactiveController());
                  }),
                );
              },
            ),
          )
        ],

      ),
    );
  }
}

 

controller_manage_page.dart 화면

 

get_put.dart

 

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

class GetPut extends GetView<DependencyUpdateController> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Dependency Test - Get.put'),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GetBuilder<DependencyUpdateController>(
                builder: (controller) {
                  return Text(
                    "숫자증가: ${controller.count}",
                    style: TextStyle(fontSize: 30),
                  );
                }
            ),
            SizedBox(
              width: 130,
              child: ElevatedButton(
                child: Text("Get.put"),
                onPressed: () {
                  print('hashCode: ' + controller.hashCode.toString());
                  controller.increase();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

 

get_lazyput.dart

 

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

class GetLazyPut extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title: Text('Dependency Test - Get.lazyPut'),),
      body: Center(
        child: ElevatedButton(
          child: Text("Get.lazyPut"),
          onPressed: () {
            Get.find<DependencyUpdateController>().increase();
          },
        ),
      ),
    );
  }

}

 

get_putaync.dart

 

import 'package:flutter/material.dart';

class GetPutAsync extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Dependency Test - Get.putAsync'),),
    );
  }
}

 

get_create.dart

 

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

class GetCreate extends StatelessWidget { 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Dependency Test - Get.create'),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            GetCreateBody('Getx Reactive #1'),
            Divider(thickness:2.0, color: Colors.black),
            GetCreateBody('Getx Reactive #2'),
          ],
        ),
      ),
    );
  }
}

class GetCreateBody extends GetWidget<DependencyReactiveController> { 

  final String _title;
  GetCreateBody(this._title);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(this._title, style: TextStyle(fontSize: 20),),
          Container(height: 10,),
          Obx((){
            return Text("${controller.count}",
              style: TextStyle(fontSize: 15),
            );
          }),
          ElevatedButton(
            child: Text("Get.create"),
            onPressed: () {
              print('hashCode: ${controller.hashCode} / ${controller.count}');
              controller.increase();
            },
          ),
        ],
      ),
    );
  }

}

 

여기서 명심해야할 사항은 Get.create 하면 독립된 controller 를 생성하여 하나의 화면에서 여러 controller 관리가 가능한 점이다. 물론 Get.put 에 tag 명을 추가하여 같은 기능을 구현가능하지만, tag 값이 유일하지 않거나 각 controller 를 추적할 필요가 없을때 사용하면 좋다.

 

 

 

시작 및 종료시의 로그는 아래와 같습니다.

 

[GETX] GOING TO ROUTE /() => GetCreate
[GETX] Instance "DependencyReactiveController" has been initialized
[GETX] Instance "DependencyReactiveController" has been initialized
I/flutter (22519): hashCode: 369992770 / 0
I/flutter (22519): hashCode: 85026251 / 0
I/flutter (22519): hashCode: 369992770 / 1
I/flutter (22519): hashCode: 85026251 / 1
[GETX] CLOSE TO ROUTE /() => GetCreate
[GETX] "DependencyReactiveController" onClose() called
[GETX] "DependencyReactiveController" deleted from memory
[GETX] "DependencyReactiveController" onClose() called
[GETX] "DependencyReactiveController" deleted from memory