Skip to content
This repository has been archived by the owner on May 7, 2023. It is now read-only.
/ persistent_state Public archive

Persist state across restarts and returns from hibernation in Flutter

License

Notifications You must be signed in to change notification settings

synw/persistent_state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

55 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Persistent state

pub package

Persist state in an Hive database across restarts and returns from hibernation

Usage

Define the state mutations

Create state update types:

enum UpdateType { intProp, stringProp, doubleProp, listProp, mapProp }

Create the state class

Create your state class and map the properties to the persitent store:

import 'package:persistent_state/persistent_state.dart';


enum UpdateType { intProp, stringProp, doubleProp, listProp, mapProp }

class AppState with PersistentState<UpdateType> {
   int get intProp => select<int>("int_prop");
   set intProp(int v) => mutate<int>("int_prop", v, UpdateType.intProp);
 
   double get doubleProp => select<double>("double_prop");
   set doubleProp(double v) =>
       mutate<double>("double_prop", v, UpdateType.doubleProp);
 
   String get stringProp => select<String>("string_prop");
   set stringProp(String v) =>
       mutate<String>("string_prop", v, UpdateType.stringProp);
 
   List<int> get listProp => select<List<int>>("list_prop");
   set listProp(List<int> v) =>
       mutate<List<int>>("list_prop", v, UpdateType.listProp);
 
   Map<String, int> get mapProp => select<Map<String, int>>("map_prop");
   set mapProp(Map<String, int> v) =>
       mutate<Map<String, int>>("map_prop", v, UpdateType.mapProp);
}   

Note: the state reads with select do not hit the database and use an in memory copy of the state

Initialize

final AppState state = AppState();
await state.init();

Mutate

All the mutations will be persisted to the database:

state.doubleProp = 3.0;

Listen to state changes

A changefeed is available:

/// [appState] is an [AppState] instance
appState.changeFeed.listen((StateUpdate change) =>
   print("State update: \n${change.type}");

Example

An example with Provider is available

About

Persist state across restarts and returns from hibernation in Flutter

Resources

License

Stars

Watchers

Forks

Packages

No packages published