Flutter 개발 시 상태관리만큼 중요한 것이 바로 종속성 관리입니다. GetX는 매우 강력하고 직관적인 종속성 관리 기능을 제공하여, 프로젝트 규모가 커져도 깔끔한 구조를 유지할 수 있도록 돕습니다.
객체 재사용: 매번 객체를 생성하지 않고 필요한 시점에 꺼내 쓸 수 있음
메모리 관리: 더 이상 필요 없는 객체는 자동으로 메모리에서 정리
코드 간결화: 복잡한 의존성 주입 코드를 대체 가능
| 구문 | 설명 | 사용 예시 |
|---|---|---|
Get.put() | 즉시 생성 후 주입 | Get.put(MyController()) |
Get.lazyPut() | 필요할 때 생성 (지연 생성) | Get.lazyPut(() => MyController()) |
Get.putAsync() | 비동기 초기화가 필요한 경우 | Get.putAsync(() async => await MyController().init()) |
Get.create() | 매번 새로운 인스턴스를 생성 | Get.create(() => MyController()) |
Get.put() vs Get.lazyPut() 비교| 항목 | Get.put() | Get.lazyPut() |
|---|---|---|
| 생성 시점 | 등록 시 즉시 생성 | 호출 시점에 생성 |
| 메모리 사용 | 항상 상주 | 필요한 순간에만 |
| 사용 목적 | 항상 필요한 객체 | 가끔 사용하는 객체 |
// Get.put 사용 예제
>>>>> main.dart
void main() async {
// 컨트롤러 등록
Get.put(BottomNavController()); // 바텀 네비게이션 컨트롤러
runApp(App());
}
>>>>> bottom_nav_controller.dart
class BottomNavController extends GetxController {
// code
}
// Get.lazyPut 사용 예제
>>>>> controller.dart
class CounterController extends GetxController {
var count = 0.obs;
void increment() => count++;
}
>>>>> main.dart
void main() {
Get.lazyPut(() => CounterController());
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(home: CounterPage());
}
}
class CounterPage extends StatelessWidget {
final controller = Get.find<CounterController>();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Obx(() => Text("Count: ${controller.count}"))),
floatingActionButton: FloatingActionButton(
onPressed: controller.increment,
child: Icon(Icons.add),
),
);
}
}
Get.put() vs Get.lazyPut() 언제 쓸까?| 구분 | Get.put() | Get.lazyPut() |
|---|---|---|
| 생성 시점 | 앱 실행 시 즉시 생성 | 필요할 때 생성 (지연) |
| 메모리 점유 | 항상 메모리에 상주 | 실제 사용할 때만 메모리에 생성 |
| 추천 상황 | 앱 전체에서 자주 쓰는 컨트롤러 | 특정 페이지에서만 쓰는 컨트롤러 |
| 예시 | 로그인 상태, 사용자 정보 등 | 특정 화면의 UI 상태 관리 등 |
✅ Tip: 자주 쓰는 전역 컨트롤러는
Get.put(),
🌱 Tip: 가볍게 쓰는 일시적인 컨트롤러는Get.lazyPut()을 추천해요!