Flutter에서 상태 관리는 애플리케이션 동작을 결정짓는 중요한 요소이다. GetX는 Flutter에서 상태 관리를 간단하고 효율적으로 할 수 있도록 도와주는 패키지임.
* GetX 외에도 Bloc, Provider 등 여러 상태관리 라이브러리가 있음.
1. GetX란?
GetX는 Flutter에서 종속성 주입(Dependency Injection), 상태 관리(State Management), 라우팅(Routing) 등을 쉽게 할 수 있도록 도와주는 패키지이다.
GetX의 주요 장점은 코드가 간결해지면서도 강력한 기능을 제공하는 점.
2. GetX 상태 관리: 단순 상태 관리와 반응형 상태 관리
GetX의 상태 관리는 크게 두 가지로 나뉨
- 단순 상태 관리(Simple State Management): 상태를 직접적으로 관리할 수 있으며, 주로 '.update()' 메서드를 사용함
- 반응형 상태 관리(Reactive State Management): 상태가 변경될 때 자동으로 UI가 업데이트 됨.
'.obs'로 선언된 변수를 사용하며, 'Obx' 또는 'GetX' 위젯을 통해 반응형 상태를 UI에 반영함.
3. 예제: CounterController를 활용한 상태 관리
3.1. CounterController 정의
먼저, 상태를 관리할 'CounterController'를 정의한다. 이 컨트롤러는 'count'라는 상태 변수를 가지고 있으며, 이 변수를 증가시키는 'increment' 메서드를 포함하고 있음
import 'package:get/get.dart';
class CounterController extends GetxController {
static CounterController get to => Get.find();
var count = 0.obs;
void increment() {
count++;
}
}
3.2. Main.dart 파일
이제 'CounterController'를 실제 Flutter 애플리케이션에서 사용하는 코드이다.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'counter_controller.dart';
void main() {
Get.put(CounterController());
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('GetX Counter Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('You have pushed the button this many times:'),
Obx(() => Text(
'${CounterController.to.count}',
style: Theme.of(context).textTheme.headline4,
)),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
CounterController.to.increment();
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
3.3. 코드 설명
- CounterController:
- 'CounterController'는 카운터 값을 저장하고 증가시키는 역할을 한다.
- 'static CounterController get to => Get.find();' 를 사용하여 컨트롤러 인스턴스 접근성 향상
- main():
- 'Get.put(CounterController());'를 사용하여 'CounterController'를 메모리에 등록한다.
- 이를 통해 애플리케이션 어디서든 이 컨트롤러를 사용할 수 있게 됨.
- HomeScreen 위젯:
- 'Obx(() => Text('${CounterController.to.count}')' 부분에서 카운터 값이 변경될 때마다 자동으로 UI를 업데이트함.
- 플로팅 액션 버튼을 눌렀을 때 'CounterController.to.incremenet()'를 호출하여 카운터 값을 증가시킴
4. 종속성 주입: Get.put()과 Get.find()
'Get.put()'은 인스턴스를 메모리에 등록하고, 'Get.find()'는 등록된 인스턴스를 검색해 반환한다.
이 방식으로 애플리케이션 전역에서 인스턴스를 관리하고 접근할 수 있는 것임.
void main() {
// CounterController를 메모리에 등록
Get.put(CounterController());
runApp(MyApp());
}
5. 결론
Flutter에서 GetX를 활용하면 복잡한 상태 관리도 간단하게 해결할 수 있다고 함. 본 포스팅은 GetX에 대한 개념 정리 및 간단한 예제를 다뤄보았고, 다음은 Flutter GetX를 활용한 채팅 모듈 구현 등 응용할 수 있는 내용을 다뤄볼 것임.