본문 바로가기

Flutter/07 State - Getx

[Flutter] GetX - Get.create 예시

이번 카테고리는 GetX 의 Get.create 의 사용 예시에 대해서 알아보겠습니다.

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

소스코드 위치 - Release 15_Get_create_example2 · mike-bskim/getx_test · GitHub

 

Release 15_Get_create_example2 · mike-bskim/getx_test

 

github.com

 

 

프로젝트 구조

/src/pages/dependencys/dependency_manage_page.dart

/src/binding/shopping_binding.dart

/src/controller/shopping_controller.dart

/src/pages/shopping/shopping_page.dart

/src/pages/shopping/shopping_item.dart

 

추가된 화면은 아래와 같다. 각 아이템의 증감분이 Total 에 모두 반영되는 예시입니다.

 

 

 

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

 

ElevatedButton(
  style: elevatedButtonStyle,
  child: const Text("Get.create 예시"),
  onPressed: () {
    Get.to(() => const ShoppingPage(), binding: ShoppingBinding());
  },
),

 

/src/binding/shopping_binding.dart

 

import 'package:get/get.dart';

import '../controller/shopping_controller.dart';

class ShoppingBinding implements Bindings {
  @override
  void dependencies() {
// different instances for different list items
    Get.create<ShoppingController>(
      () => ShoppingController(),
    );

// Separate instance to display total
    Get.put<ShoppingController>(
      ShoppingController(),
      tag: 'total',
    );
  }
}

 

/src/controller/shopping_controller.dart

 

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

class ShoppingController extends GetxController {
  var quantity = 0.obs;
  var total = 0.obs;

  @override
  void onClose() {
    debugPrint(hashCode.toString());
    super.onClose();
  }
}

 

/src/pages/shopping/shopping_page.dart

 

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

import '../../controller/shopping_controller.dart';
import 'shopping_item.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text("Get.create 예시"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: Column(
            children: [
              Obx(
                () => Text(
                  'Total: ${Get.find<ShoppingController>(tag: 'total').total.value}',
                  style: const TextStyle(fontSize: 20), // total
                ),
              ),
              Expanded(
                child: ListView.builder(
                  // shrinkWrap: true,
                  itemCount: 20,
                  itemBuilder: (context, index) {
                    return ShoppingItem(
                      item: 'Item No. ${(index+1).toString()}',
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

 

/src/pages/shopping/shopping_item.dart

Get.find() 생략 - 상위위젯(ShoppingPage) 로 이동시 이미 바인딩되어서 하위위젯(ShoppingItem)에서도 직접 접근이 가능 => dependency_manage_page.dart 내부에서 "Get.to(() => const ShoppingPage(), binding: ShoppingBinding());", 

 

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

import '../../controller/shopping_controller.dart';

class ShoppingItem extends StatelessWidget {
  final String item;
  ShoppingItem({Key? key, required this.item}) : super(key: key);

  // injected by Get.create
  final ShoppingController controller = Get.find();
  // injected by Get.put
  final ShoppingController controllerTotal = Get.find(tag: 'total');

  @override
  Widget build(BuildContext context) {
    ButtonStyle elevatedButtonStyle =
        ElevatedButton.styleFrom(minimumSize: const Size(30.0, 20.0));
    // debugPrint(controller.hashCode.toString());

    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        SizedBox(
          width: 100,
          child: Text(item),
        ),
        ElevatedButton(
          style: elevatedButtonStyle,
          onPressed: () {
            controller.quantity.value++; // create
            // Get.find<ShoppingController>(tag: 'total').total.value++; // put
            controllerTotal.total.value++; // put
            // debugPrint(
            //     Get.find<ShoppingController>(tag: 'total').hashCode.toString());
          },
          child: const Text('+'),
        ),
        SizedBox(
          width: 40,
          child: Obx(
            () => Text(
              textAlign: TextAlign.center,
              controller.quantity.value
                  .toString(), // using same instance of Get.find
            ),
          ),
        ),
        ElevatedButton(
          style: elevatedButtonStyle,
          onPressed: () {
            controller.quantity.value--; // create
            // injected by Get.put
            // Get.find<ShoppingController>(tag: 'total').total.value--;
            controllerTotal.total.value--; // put
          },
          child: const Text('-'),
        ),

      ],
    );
  }
}

 

 

 

 

 

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