StateNotifier<T> class abstract

An observable class that stores a single immutable state.

It can be used as a drop-in replacement to ChangeNotifier or other equivalent objects like Bloc. Its particularity is that it tries to be simple, yet promote immutable data.

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

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

Example: Counter

StateNotifier is designed to be subclassed. We first need to pass an initial value to the super constructor, to define the initial state of our object.

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

We can then expose methods on our StateNotifier to allow other objects to modify the counter:

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

  void increment() => state++;
  void decrement() => state--;
}

assigning state to a new value will automatically notify the listeners and update the UI.

Then, the object can either be listened like with StateNotifierBuilder/StateNotifierProvider using package:flutter_state_notifier or package:riverpod.

See also:

Constructors

StateNotifier(T _state)
Initialize state.

Properties

debugState → T
A development-only way to access state outside of StateNotifier.
no setter
hashCode int
The hash code for this object.
no setterinherited
hasListeners bool
If a listener has been added using addListener and hasn't been removed yet.
no setter
mounted bool
Whether dispose was called or not.
no setter
onError ErrorListener?
A callback for error reporting if one of the listeners added with addListener throws.
getter/setter pair
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
state ↔ T
The current "state" of this StateNotifier.
getter/setter pair
stream Stream<T>
A broadcast stream representation of a StateNotifier.
no setter

Methods

addListener(Listener<T> listener, {bool fireImmediately = true}) RemoveListener
Subscribes to this object.
dispose() → void
Frees all the resources associated to this object.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited
updateShouldNotify(T old, T current) bool
Whether to notify listeners or not when state changes

Operators

operator ==(Object other) bool
The equality operator.
inherited