2022. 1. 20. 18:12ㆍFlutter

GetX의 상태 관리에는 크게 두 가지의 방법이 있다.
그중 단순 상태 관리에 대해 먼저 알아보자
📢Controller
// simple_controller.dart
import 'package:get/get.dart';
class SimpleController extends GetxController {
int count = 0;
void increase() {
count++;
update();
}
}
먼저 단순 상태 관리를 위한 controller를 만들었다
count 변수와 count 변수 증가를 위한 increase 메소드가 있다
값이 바뀜을 화면에 알려주기 위해 update()가 들어간다
📢Main
// main.dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getstudy/controller/simple_controller.dart';
import 'package:getstudy/page/simple_state.dart';
void main() {
runApp(
GetMaterialApp(
home: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Get.put(SimpleController());
return Scaffold(
appBar: AppBar(
title: Text("GetX"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
Get.to(() => SimpleState());
},
child: Text(
"단순 상태관리",
style: TextStyle(
fontSize: 20,
),
),
),
],
),
),
);
}
}
메인화면.
단순 상태 관리 결과값을 확인하는 페이지(SimpleState)로 넘어가기 위한 버튼을 하나 두었다.
build메소드 안에 아까 만든 controller를 등록한다
Get.put()을 통해 등록한 controller는 어디서든 사용이 가능하다
📢SimpleState
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getstudy/controller/simple_controller.dart';
class SimpleState extends StatelessWidget {
const SimpleState({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("단순 상태관리"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GetBuilder<SimpleController>(
builder: (controller) {
return Text(
"${controller.count}",
style: TextStyle(
fontSize: 30,
),
);
},
),
ElevatedButton(
onPressed: () {
Get.find<SimpleController>().increase();
},
child: Text("증가"),
)
],
),
),
);
}
}
count를 출력하며, count를 변화시키기 위한 버튼이 있는 페이지이다
GetBuilder()를 통해 화면에 변수를 보여줄 수 있다.
Get.find()를 통해 생성해둔 controller를 불러올 수 있다.


count가 잘 증가하는 것을 확인할 수 있다✨
+) Get.find() 코드를 줄이는 법
Get.find() 코드를 작성할 때 조금 길게 느껴졌다면 간단히 줄일 수 있는 방법이 있다!
1. Controlle를 static 처리하기
// simple_controller.dart
class SimpleController extends GetxController {
static SimpleController get to => Get.find();
...
}
SimpleController 클래스 안에 위와 같은 코드를 추가해주면
// simple_state.dart
// 전
Get.find<SimpleController>().increase();
// 후
SimpleController.to.increase();
다음과 같이 소괄호나 꺾쇠 없이 조금 더 간단하게 작성할 수 있다.
2. GetView 사용하기
static처리보다 더 간단하게 접근하는 방법이다
// simple_state.dart
// 전
class SimpleState extends StatelessWidget{}
// 후
class SimpleState extends GetView<SimpleController>{}
Get.find()를 사용할 클래스에 StatelessWidget대신 GetView를 상속시키는 것이다
GetView의 꺾쇠 안에는 사용할 컨트롤러를 넣어준다.
위 코드를 보면 SimpleState 클래스의 controller는 모두 SimpleController라는 것을 알려주는 것이다
// simple_state.dart
// 전
Get.find<SimpleController>().increase();
// 후
controller.increase();
나름 매우 매우 간단해진 것을 볼 수 있다
'Flutter' 카테고리의 다른 글
#3-1 GetX - 종속성관리 : 인스턴스 메서드 (0) | 2022.01.21 |
---|---|
#2-2 GetX - 상태관리 : 반응형 상태 관리 (0) | 2022.01.21 |
#1 GetX - 라우트 관리 (0) | 2022.01.20 |
#0 Getx는 무엇인가? (0) | 2022.01.20 |
안드로이드 에뮬레이터 스킨 없애기 (0) | 2022.01.19 |