flutter/기타

Getx - Reactive State manager 방식들

coens 2023. 9. 4. 00:06

사용하는 방법들이 여러가지가 있어서 간단하게 해서 정리나열을 해봄

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

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: PersonalCard(),
    );
  }
}

class Person {
  int age = 0;
  String? name = "";
}

class Controller extends GetxController {
  final person = Person().obs;

  void updateInfo() {
    person.update((val) {
      val?.age++;
      val?.name = "coens";
    });
  }
}

class PersonalCard extends StatelessWidget {

  final Controller controller = Get.put(Controller());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          GetX<Controller>(
            builder: (_) => Text('${controller.person().age} / ${controller.person().name}'),
          ),
          GetX<Controller>(
            builder: (controller) => Text('${controller.person.value.age} / ${controller.person.value.name}'),
          ),
          Obx(
            () => Text('${controller.person().age} / ${controller.person().name}'),
          ),
          GetX(
            init: Controller(),
            builder: (_)=>Text('${Get.find<Controller>().person().age} / ${Get.find<Controller>().person().name}'),
          ),
          GetX(
            init: Controller(),
            builder: (controller)=>Text('${controller.person.value.age} / ${controller.person.value.name}'),
          ),
          ElevatedButton(
            onPressed: () {
              controller.updateInfo();
            },
            child: Text("updateInfo"),
          )
        ],
      ),
    );
  }
}