Flutter GetxController GetxService

이건선·2023년 7월 24일
0

Flutter

목록 보기
18/30

GetxController

GetxController는 일반적으로 화면 (페이지 또는 뷰)에 관련된 로직을 담당합니다. 각 컨트롤러는 해당 페이지가 메모리에서 제거될 때 함께 제거됩니다. 이로 인해 메모리 누수를 방지할 수 있습니다.

class HomeController extends GetxController {
  var count = 0.obs; 

  incrementCount() {
    count++;
  }
}

여기서 .obs는 GetX에게 이 변수를 "관찰"하도록 지시하는 GetX의 문법입니다. 그리고 이 변수에 변화가 생기면 관련 UI를 자동으로 업데이트합니다.

GetxService

GetxService는 애플리케이션 전반에서 사용되는 로직을 담당합니다. 따라서 어느 화면에서든 접근할 수 있어야 하며, 애플리케이션의 생명 주기 동안 지속적으로 메모리에 유지됩니다.

예를 들어, API 통신이나 로컬 데이터베이스의 CRUD 작업을 담당하는 Service는 다음과 같습니다.

class ApiService extends GetxService {
  Future<String> fetchData() async {
    await Future.delayed(Duration(seconds: 1)); // Let's pretend we're getting data from an API
    return "Fetched Data";
  }
}

이제 'Get.put' 또는 'Get.lazyPut'을 사용하여 이들 컨트롤러와 서비스를 초기화하고, 'Get.find'로 해당 인스턴스에 접근할 수 있습니다.

Get.put
컨트롤러를 즉시 초기화합니다. 주로 앱이 시작할 때 필요한 컨트롤러를 초기화하는 데 사용됩니다.

void main() {
  Get.put(ApiService());
  runApp(MyApp());
}

Get.lazyPut
컨트롤러를 지연 초기화합니다. 즉, 실제로 컨트롤러를 사용할 때까지 초기화하지 않습니다. 이렇게 하면 앱의 성능을 향상시킬 수 있습니다.

void main() {
  Get.lazyPut<HomeController>(() => HomeController());
  runApp(MyApp());
}

Get.find
이미 초기화된 컨트롤러 또는 서비스의 인스턴스를 얻는 데 사용됩니다.

class HomePage extends StatelessWidget {
  final ApiService apiService = Get.find<ApiService>();
  final HomeController homeController = Get.find<HomeController>();

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home')),
      body: Center(
        child: Column(
          children: [
            Text('API Response: ${apiService.fetchData()}'),
            Text('Count: ${homeController.count}'),
          ],
        ),
      ),
    );
  }
}

GetBuilder, GetX, Obx

GetX에서 제공하는 상태 관리 메서드들입니다. 각각의 메서드는 조금씩 다른 방식으로 사용되며, 상황에 따라 선택하여 사용할 수 있습니다.

1. GetBuilder

GetBuilder는 가장 기본적인 GetX의 상태 관리 방법입니다. GetBuilder를 사용하려면, GetxController를 상속받은 컨트롤러 클래스를 만들어야 합니다.

class CountController extends GetxController {
  int count = 0;

  void increment() {
    count++;
    update();
  }
}

이렇게 만든 컨트롤러를 UI에 바인딩하려면 GetBuilder를 사용하면 됩니다.

GetBuilder<CountController>(
  init: CountController(),
  builder: (controller) => Text('Current count: ${controller.count}'),
),

2. GetX

GetXObx와 같은 반응형 상태 관리 방법입니다. GetX는 .obs를 통해 Observable로 변환된 변수의 변화를 감지하고 UI를 업데이트합니다.

class CountController extends GetxController {
  var count = 0.obs;

  void increment() {
    count.value++;
  }
}

UI에 바인딩하려면 GetX를 사용하면 됩니다.

GetX<CountController>(
  init: CountController(),
  builder: (controller) => Text('Current count: ${controller.count}'),
),

3. Obx

ObxGetX와 같은 방식으로 사용하지만, GetX보다 더 간단한 문법으로 사용할 수 있습니다. 하지만, Obx는 반응형 값에 직접적으로 접근해야 하기 때문에 좀 더 주의가 필요합니다.

Obx(() => Text('Current count: ${Get.find<CountController>().count}')),
profile
멋지게 기록하자

1개의 댓글

comment-user-thumbnail
2023년 7월 24일

개발자로서 성장하는 데 큰 도움이 된 글이었습니다. 감사합니다.

답글 달기