StateNotifier
If you have a more complex state consider using the StateNotifier class instead of SimpleNotifier.
A StateNotifier stores a single immutable state.
An immutable state is an instance of one Class that overrides ==
and hashCode
. For example you could use equatable or freezed to create an immutable Class.
#
With equatableAdd equatable as a dependency in your pubspec.yaml
file
Now you can create a Class to manage your state
#
With freezedTo use freezed you need build_runner and freezed_annotation
in your pubspec.yaml
file (replace latest_version
with the latest version of each dependency)
If you have conflicts when you try to install freezed check the oficial documentation https://pub.dev/packages/freezed
next run the next command to generate the .frezeed.dart
files
Now you can use the LoginState
class to create a StateNotifier
info
If you only want to update the state of your StateNotifier
but you don't want to notify to the listeners (don't rebuild the Consumer
widgets and don't listen the changes in the ProviderListener
widget)
you can use the onlyUpdate
method in your StateNotifier
.
Next you need to create a StateProvider
and use the Consumer
widget to listen the changes in your state
Also you can use the select
method of your provider to only rebuild your Consumer
when is need it.
For example the next code only rebuilds the Consumer widget when the email
in our LoginState
has changed.
here we use ref.select
to direct access to the value returned by loginProvider.select
but if you want get the notifier linked to loginProvider
you can use ref.watch
with loginProvider.select
note
Also you can use the when
method for a more complex condition.
info
In the same way you can listen the changes of your StateNofier
using the ProviderListener
widget or using a StreamSubscription
Also the StateNotifier
class allows you to listen when the state is going to change and listen when the state has changed.