seong
Flutter - ValueNotifier 본문
Flutter에는 상태(State)가 존재하고 상태를 관리해줄 필요성이 있다.
상태를 관리 해주는 방법으로는 다양하게 Flutter에서 제공하는 ValueNotifier,ChangeNotifier,StateNotifer등 과 라이브러리(GetX,RiverPod,Provider,Bloc 등)를 활용하는 여러가지 방법이 있다.
이번에는 ValueNotifier에 대해 공부 해볼 것이다.
https://api.flutter.dev/flutter/foundation/ValueNotifier-class.html
공식 문서
A ChangeNotifier that holds a single value.
When value is replaced with something that is not equal to the old value as evaluated by the equality operator ==, this class notifies its listeners.
- 단일 value를 가지고 있는 ChangeNotifier 이다.
- value가 변경 될 때, 이전 값과 다르다면 listener에게 알려준다.
ValueNotifier의 클래스 구현부 살펴보기
1. ValueNotifier는 ChangeNotifier,ValueListenable를 상속 받고 있다.
2. newValue와 _value를 비교해 바뀌었다면 값을 변경 후 리스너에게 알려준다.
간단한 Counter 예제
- 한가지의 value (count)를 가지고 있다.
- setState없이 ValueListenableBuilder 위젯으로 변경사항에 대해 적용을 한다.
class Counter{
ValueNotifier<int> count = ValueNotifier<int>(0);
void add(){
count.value++;
print("value : ${count}");
}
}
class ValueNotifierScreen extends StatefulWidget {
const ValueNotifierScreen({super.key});
@override
State<ValueNotifierScreen> createState() => _ValueNotifierScreenState();
}
class _ValueNotifierScreenState extends State<ValueNotifierScreen> {
@override
Widget build(BuildContext context) {
final Counter counter = Counter();
return Scaffold(
appBar: AppBar(
title: Text("ValueNotifier"),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ValueListenableBuilder(
valueListenable: counter.count,
builder: (BuildContext context, value, Widget? child) {
return Text("${value}");
},
),
TextButton(
child: Text("Add"),
onPressed: () {
counter.add();
},
),
],
),
),
);
}
}
'Flutter > Flutter' 카테고리의 다른 글
Flutter - BottomSheet 높이 키보드 영역 만큼 동적으로 조절 (0) | 2024.01.23 |
---|---|
Flutter - Scaffold 속성 (0) | 2024.01.23 |
Flutter - 특정 버전으로 변경 (0) | 2023.12.28 |
Flutter - 현재 페이지 경로 가져오기 (0) | 2023.12.27 |
Flutter - 앱 가로 모드 방지 (1) | 2023.12.03 |