seong

Flutter - ValueNotifier 본문

Flutter/Flutter

Flutter - ValueNotifier

hyeonseong 2024. 1. 2. 18:25

Flutter에는 상태(State)가 존재하고 상태를 관리해줄 필요성이 있다.

상태를 관리 해주는 방법으로는 다양하게 Flutter에서 제공하는 ValueNotifier,ChangeNotifier,StateNotifer등 과 라이브러리(GetX,RiverPod,Provider,Bloc 등)를 활용하는 여러가지 방법이 있다.

이번에는 ValueNotifier에 대해 공부 해볼 것이다.

 

https://api.flutter.dev/flutter/foundation/ValueNotifier-class.html

 

ValueNotifier class - foundation library - Dart API

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. Limitations Because this class only notifies listeners when th

api.flutter.dev

공식 문서 

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();
              },
            ),
          ],
        ),
      ),
    );
  }
}