StateNotifier<T> class Null safety

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. [...]
read-only
hashCode int
The hash code for this object. [...]
read-only, inherited
hasListeners bool
If a listener has been added using addListener and hasn't been removed yet.
read-only
mounted bool
Whether dispose was called or not.
read-only
onError ErrorListener?
A callback for error reporting if one of the listeners added with addListener throws. [...]
read / write
runtimeType Type
A representation of the runtime type of the object.
read-only, inherited
state ↔ T
The current "state" of this StateNotifier. [...]
@protected, @protected, read / write
stream Stream<T>
A broadcast stream representation of a StateNotifier.
read-only

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 non-existent 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