StateNotifier<T> class

An observable class that stores a single immutable state.

This class can be considered as a fork of ValueNotifier from Flutter, with subtle API changes and performance improvements.

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.

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 StateNofierBuilder/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, 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. [...]
@mustCallSuper
noSuchMethod(Invocation invocation) → dynamic
Invoked when a non-existent method or property is accessed. [...]
inherited
toString() String
Returns a string representation of this object.
inherited

Operators

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