Flutter StateNotifierBuilder 사용법

개발하자 백조·2022년 9월 21일
0

++ state notifier의 값이 바뀔때마다 화면을 rebuild 해주고 싶을 때 사용 ++


데이터가 들어올 때마다 ListTile 의 색을 바꾸기 위해 사용했다.

먼저 내가 사용할 StateNotifier 클래스 객체를 만들어주고 초기값을 자유롭게 지정해준다.

FireLocation _fireLocation = context.read<FireLocation>();

그리고 그 객체를 stateNotifier 변수에 넣어준다.

return StateNotifierBuilder(
      stateNotifier: _fireLocation,
      builder: (BuildContext context, value, Widget? child) {
        return ListView.separated(
          itemCount: _treeList.length,
          separatorBuilder: (_, __) => Divider(),
          itemBuilder: (context, index) {
            List _nextTree = _treeList[index]["Children"];
            return ListTile(
                title: Text(_treeList[index]["Text"]),
                tileColor: (context
                    .watch<FireLocation>()
                    .getLocationId()
                    .contains(_treeList[index]["Id"]))
                    ? Colors.redAccent
                    : Colors.white,
            );
          },
        );
      },
    );

다른 세부 코드는 다 빼고 이런 식으로 하면 FireLocation의 state가 바뀔 때마다 해당 정보를 토대로 tileColor가 바뀌게 된다.

setState 없이 어떻게 즉각적으로 색을 바꿀 수 있을까 싶었는데 이런 방법이 있었군!
내가 원하는 대로 동작하는 것을 볼 수 있어서 좋았다.

profile
개발자로서 100가지 일을 해보고 싶은 조경현의 개발 블로그

0개의 댓글