Persistent state
Since flutter_meedu:^6.2.3 the StateNotifier class allows you to keep the state of your Notifiers even if the app was killed (very useful when you want to add OFFLINE support to your apps).
For this just use the PersistentStateMixin mixin and the PersistentStateStorage class then you must override the all properties and methods necessary to persist the state of your StateNotifier.
Considere the next example you want to build a city picker page and every time that you show that page you have to make an API request to get a list of cities. So, why don't you cache the cities and the next time that you show the city picker you will be using a cached list of cities instead of making a new API request?
Example using Hive as database#
The next class will be used for you state
Next you have to create your storage
note
Note that in the above code we use jsonEncode to store the json state as a string to avoid to define custom TypeAdapters for Hive. Also we use jsonDecode to convert the json string to a Map.
You are free to use any other Database.
Now in your main inject a Hive box as a dependency.
Now we must create the StateNotifier and use the PersistentStateMixin mixin.
In the above code the PersistentStateMixin mixin forces you to override:
storageKey: an unique string used to idenfier your state in the storage.storage: one instance of a class that implementsMyPersistentStorageand all logic to save and read your state.toJson: a method to parse your current state as a json and save it in the storage. This method will be called every time that the state of your Notifier changes. IftoJsonreturns null when the current state saved in your storage won't be modified.fromJson: This method is called only once when thePersistentStateMixinis detecting that your are trying to get your current state for the first time then is the moment to check if a previous state was saved in the storage, next thefromJsonmethod will be used to parse the json saved in your storage into one instance of yourState.
note
You can override the onPersistentStateError method to listen when a state couldn't be saved or it couldn't be parsed.
success
You can check a complete example using freezed unions here