패키지, 저장소 및 앱 카테고리 검색

패키지 상세v1.0.0

flutter_state_notifier

state_notifier의 Flutter 바인딩, 예를 들어 StateNotifierProvider 및 StateNotifierBuilder

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
2.1만
좋아요
56
Pub 점수
160

패키지 설치

flutter pub add flutter_state_notifier

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

flutter_state_notifier는 state_notifier 패키지에 대한 플러터 전용 바인딩을 제공하여 StateNotifierProvider 및 StateNotifierBuilder와 같은 위젯을 통해 효율적인 상태 관리를 가능하게 합니다. 플러터의 위젯 트리와 원활하게 통합되어 상태 변경에 따라 반응형 업데이트를 지원합니다. 확장성과 성능을 고려해 설계되었으며, 복잡한 앱 상태를 지원하면서도 관심사의 명확한 분리를 유지합니다. 예측 가능한 상태 전이와 여러 위젯 간 상태 업데이트에 대한 세밀한 제어가 필요한 앱에 적합합니다.

사용 사례

  • 복잡한 앱 상태 관리
  • 상태에 따라 반응형 UI 업데이트
  • 대규모 앱에서의 확장 가능한 상태 관리
  • 다른 상태 관리 솔루션과의 통합
  • 재사용 가능한 상태 로직 빌드
  • 비동기 상태 작업 지원

주요 기능

  • 의존성 주입을 위한 StateNotifierProvider
  • 반응형 UI 렌더링을 위한 StateNotifierBuilder
  • 세밀한 상태 변경 추적
  • 비동기 상태 처리 지원
  • 조합 가능한 상태 로직
  • Flutter 빌드 시스템과의 통합

적합한 대상

  • state_notifier를 사용하는 개발자
  • 확장 가능한 상태 관리가 필요한 앱
  • 테스트 가능성과 유지보수성을 우선시하는 팀
  • 비즈니스 로직과 UI를 분리해야 하는 프로젝트
  • 복잡한 상태 요구 사항을 가진 Flutter 앱

고려 사항

  • state_notifier 개념을 이해해야 합니다
  • 간단한 앱에 복잡성을 추가할 수 있음
  • 비동기 상태 전환을 신중하게 처리해야 합니다
  • 중소에서 대규모 애플리케이션에 가장 적합
  • 대안에 비해 내장된 디버깅 도구가 제한적

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

pub package Welcome to state_notifier~

This package is a recommended solution for managing state when using Provider or Riverpod.

Long story short, instead of extending ChangeNotifier, extend StateNotifier:

class City {
  City({required this.name, required this.population});
  final String name;
  final int population;
}


class CityNotifier extends StateNotifier<List<City>> {
  CityNotifier() : super(const <City>[]);

  void addCity(City newCity) {
    state = [
      ...state,
      newCity,
    ];
  }
}

Motivation

The purpose of StateNotifier is to be a simple solution to control state in an immutable manner.
While ChangeNotifier is simple, through its mutable nature, it can be harder to maintain as it grows larger.

By using immutable state, it becomes a lot simpler to:

  • compare previous and new state
  • implement an undo-redo mechanism
  • debug the application state

Good practices

DON'T update the state of a StateNotifier outside the notifier

While you could technically write:

class Counter extends StateNotifier<int> {
  Counter(): super(0);
}

final notifier = Counter();
notifier.state++;

That is considered an anti-pattern (and your IDE should show a warning).

Only the StateNotifier should modify its state. Instead, prefer using a method:

class Counter extends StateNotifier<int> {
  Counter(): super(0);

  void increment() => state++:
}

final notifier = Counter();
notifier.increment();

The goal is to centralize all the logic that modifies a StateNotifier within the StateNotifier itself.

FAQ

Why are listeners called when the new state is == to the previous state?

You may realize that a StateNotifier does not use == to verify that the state has changed before notifying for changes.

This behavior is voluntary, for performance reasons.

The reasoning is that StateNotifier is typically used with complex objects, which often override == to perform a deep comparison.
But performing a deep comparison can be a costly operation, especially since it is common for the state to contain lists/maps.
Similarly, for complex states, it is rare that when calling notifier.state = newState, the new and previous states are the same.

As such, instead of using ==, StateNotifier relies on identical to compare objects.
This way, when using StateNotifier with simple states like int/enums, it will correctly filter identical states. At the same time, this preserves performance on complex states, as identical will not perform a deep object comparison.

Using custom notification filter logic

You can override the method updateShouldNotify(T old,T current) of a StateNotifier to change the default behaviour, such as for:

  • using == instead of identical to filter updates, for deep state comparison
  • always returning true to revert to older behaviors of StateNotifier
  @override
  bool updateShouldNotify(User old, User current) {
    /// only update the User content changes, even if using a different instance
    return old.name != current.name && old.age != current.age;
  }

Usage

Integration with Freezed

While entirely optional, it is recommended to use StateNotifier in combination with Freezed.
Freezed is a code-generation package for data-classes in Dart, which automatically generates methods like copyWith and adds support for union-types.

A typical example would be using Freezed to handle data vs error vs loading states. With its union-types, it can lead to a significant improvement in maintainability as it:

  • ensures that your application will not enter illogical states (such as both having a "data" and being in the "loading" state)
  • ensures that logic handles all possible cases. Such as forcing that the loading/error cases be checked before trying to access the data.

The idea is that, rather than defining the data, error and loading state in a single object like:

class MyState {
  MyState(...);
  final Data data;
  final Object? error;
  final bool loading;
}

We can use Freezed to define it as:

@freezed
class MyState {
  factory MyState.data(Data data) = MyStateData;
  factory MyState.error(Object? error) = MyStateError;
  factory MyState.loading() = MyStateLoading;
}

That voluntarily prevents us from doing:

void main() {
  MyState state;
  print(state.data);
}

Instead, we can use the generated map method to handle the various cases:

void main() {
  MyState state;
  state.when(
    data: (state) => print(state.data),
    loading: (state) => print('loading'),
    error: (state) => print('Error: ${state.error}'),
  );
}
Integration with provider/service locators

StateNotifier is easily compatible with provider through an extra mixin: LocatorMixin.

Consider a typical StateNotifier:

class Count {
  Count(this.count);
  final int count;
}

class Counter extends StateNotifier<Count> {
  Counter(): super(Count(0));

  void increment() {
    state = Count(state.count + 1);
  }
}

In this example, we may want to use Provider.of/context.read to connect our Counter with external services.

To do so, simply mix-in LocatorMixin as such:

class Counter extends StateNotifier<Count> with LocatorMixin {
// unchanged
}

That then gives you access to:

  • read, a function to obtain services
  • update, a new life-cycle that can be used to listen to changes on a service

We could use them to change our Counter incrementation to save the counter in a DB when incrementing the value:

class Counter extends StateNotifier<Count> with LocatorMixin {
  Counter(): super(Count(0))

  void increment() {
    state = Count(state.count + 1);
    read<LocalStorage>().writeInt('count', state.count);
  }
}

Where Counter and LocalStorage are defined using provider this way:

void main() {
  runApp(
    MultiProvider(
      providers: [
        Provider(create: (_) => LocalStorage()),
        StateNotifierProvider<Counter, Count>(create: (_) => Counter()),
      ],
      child: MyApp(),
    ),
  );
}

Then, Counter/Count are consumed using your typical context.watch/Consumer/context.select/...:

@override
Widget build(BuildContext context) {
  int count = context.watch<Count>().count;

  return Scaffold(
    body: Text('$count'),
    floatingActionButton: FloatingActionButton(
      onPressed: () => context.read<Counter>().increment(),
      child: Icon(Icons.add),
    ),
  );
}

Testing

When using LocatorMixin, you may want to mock a dependency for your tests.
Of course, we still don't want to depend on Flutter/provider to do such a thing.

Similarly, since state is protected, tests need a simple way to read the state.

As such, LocatorMixin also adds extra utilities to help you with this scenario:

myStateNotifier.debugMockDependency<MyDependency>(myDependency);
print(myStateNotifier.debugState);
myStateNotifier.debugUpdate();

As such, if we want to test our previous Counter, we could mock LocalStorage this way:

test('increment and saves to local storage', () {
  final mockLocalStorage = MockLocalStorage();
  final counter = Counter()
    ..debugMockDependency<LocalStorage>(mockLocalStorage);

  expect(counter.debugState, 0);

  counter.increment(); // works fine since we mocked the LocalStorage

  expect(counter.debugState, 1);
  // mockito stuff
  verify(mockLocalStorage.writeInt('int', 1));
});

Note: LocatorMixin only works on StateNotifier. If you try to use it on other classes by using with LocatorMixin, it will not work.

Sponsors

카테고리

의존성

의존성 목록 3 개

소스 저장소

이 패키지를 사용하는 프로젝트