728x90
반응형 상태관리는 GetxController 를 상속받지 않아도 된다.
대신 하나 하나의 변수에 obs를 붙여서 listening을 한다. 메소드 내에 update()도 필요 없다.
GetX 반응형 상태관리 예제
import 'package:get/get.dart';
class CountController extends GetxController {
RxInt counter = 0.obs;
// 반응형은 obs 를 붙이고 int 형에서 RxInt 형으로 변경
// RxDouble, RxString, Rx<Class명>, RxList<String>, Rx<ENUM명>
void increment() {
counter++;
// update(); 는 필요 없다.
}
void decrement() {
counter--;
}
void putNumber(int val){
counter(val);
}
@override
void onInit() {
//ever(counter, (_) => print('매번 호출'));
//once(counter, (_) => print('한번만 호출'));
//debounce(counter, (_) => print('마지막 변경에 한번만 호출'), time: Duration(seconds: 1) );
super.onInit();
}
}
|
MaterialApp → GetMaterialApp 으로 변경한다.
실제 사용하는 곳에서 인스턴스를 생성해야 한다. Get.put(CountController());
단순 상태관리는 GetBuilder를 사용했다면, 반응형은 Obx 와 GetX 두 가지 방법이 있다.
비교적 사용법이 간단한 Obx 를 많이 사용한다.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'controller.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
Get.put(CountController());
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'You have pushed the button and count :',
),
Obx(() {
//print('Update UI'); // 화면 렌더링을 확인하고 싶을 때
return Text(
'${Get.find<CountController>().counter.value}',
style: Theme.of(context).textTheme.headline4,
);
} ),
],
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: () {
Get.find<CountController>().increment();
},
backgroundColor: Colors.green,
child: const Icon(Icons.add)),
SizedBox(width: 10, height: 10,), // 여백을 만들기 위해서 넣음.
FloatingActionButton(
onPressed: () {
Get.find<CountController>().decrement();
},
backgroundColor: Colors.pink,
child: const Icon(Icons.remove)),
SizedBox(width: 10, height: 10,), // 여백을 만들기 위해서 넣음.
FloatingActionButton(
onPressed: () {
Get.find<CountController>().putNumber(5);
},
backgroundColor: Colors.blue,
child: const Text('5')),
],
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
|
Obx 는 화살표 함수(람다식 표현)로 수정할 수 있으나, 로그 확인을 위해서 print 함수를 찍어서 알아보기 위함이다.
Rx 타입 자료형
class User{
String name;
int age;
User({this.name, this.age})
}
enum NUM {FIRST,SECOND} class CountReactiveGetx extends GetxController{
RxInt count = 0.obs;
RxDouble _double = 0.0.obs;
RxString value = "".obs;
Rx<NUM> nums = NUM.FIRST.obs;
Rx<User> user = User(name:'Json',age:10).obs;
RxList<String> list=[].obs;
void increase(){
count++;
_double++;
_double(424);
nums(NUM.SECOND);
user(User());
user.update((_user){ _user.name='James'});
//list.addAll();
//list.add();
//list.addIf(user.value.name == 'Json','OKAY') //(조건,추가할 요소)
}
}
|
출처 : https://www.youtube.com/watch?v=TjC1ka8fZJw 유투브 영상
728x90
'Flutter 앱 > 상태관리' 카테고리의 다른 글
Flutter Riverpod - NotifierProvider.family (0) | 2023.12.11 |
---|---|
Flutter Riverpod - NotifierProvider (0) | 2023.12.11 |
Flutter riverpod - StateProvider (0) | 2023.11.23 |
Flutter GetX (단순 상태관리) (0) | 2022.06.23 |
Flutter Provider (상태관리) (0) | 2022.06.21 |