Orientação gerada a partir de informações públicas. Apenas para referência.
flutter_state_notifier fornece vinculações específicas do Flutter para o pacote state_notifier, permitindo gerenciamento eficiente de estado por meio de widgets como StateNotifierProvider e StateNotifierBuilder. Integra-se perfeitamente à árvore de widgets do Flutter, possibilitando atualizações reativas com base em mudanças de estado. Projetado para escalabilidade e desempenho, suporta estados complexos de aplicativos mantendo uma separação clara de responsabilidades. O pacote é ideal para aplicações que exigem transições de estado previsíveis e controle granular sobre atualizações de estado em múltiplos widgets.
Casos de uso
Gerenciando o estado complexo do aplicativo
Atualizações de interface reativas com base no estado
Gerenciamento de estado escalonável em aplicativos grandes
Integração com outras soluções de gerenciamento de estado
Construindo lógica de estado reutilizável
Suporte a operações assíncronas de estado
Principais recursos
StateNotifierProvider para injeção de dependência
StateNotifierBuilder para renderização reativa da interface do usuário
Rastreamento de alterações de estado granular
Suporte para manipulação assíncrona de estado
Lógica de estado componível
Integração com o sistema de build do Flutter
Indicado para
Desenvolvedores usando state_notifier
Aplicativos que precisam de gerenciamento de estado escalável
Equipes que priorizam testabilidade e manutenibilidade
Projetos que exigem separação da lógica de negócios da interface do usuário
Aplicativos Flutter com requisitos complexos de estado
Considerações
Requer conhecimento dos conceitos de state_notifier
Pode adicionar complexidade a aplicativos simples
Requer manuseio cuidadoso das transições de estado assíncronas
Mais adequado para aplicativos médios a grandes
Ferramentas de depuração internas limitadas em comparação com alternativas
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
Welcome to state_notifier~
This package is a recommended solution for managing state when using Provider or Riverpod.
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:
classCounterextendsStateNotifier<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:
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
@overrideboolupdateShouldNotify(User old, User current) {
/// only update the User content changes, even if using a different instancereturn 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:
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:
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 LocalStorageexpect(counter.debugState, 1);
// mockito stuffverify(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.