State Persistence - Persist state across app launches. By default this library store state as a local JSON file called `data.json` in the applications data directory. Maintainer: @slightfoot

Last update: Dec 23, 2021

Flutter Community: state_persistence

State Persistence

pub package

Persist state across app launches. By default this library store state as a local JSON file called data.json in the applications data directory. You can change this filename by providing another storage mechanism.

If you do not want to store your persisted app state as a JSON file you can extend PersistedStateStorage and provide your own methods for saving and loading data. E.g shared_preferences or sqflite. For those of you that are ambitious you could even store your state on the web or even in Firebase.

To change the persisted state simply modify the values in the data map. These changes will automatically be persisted to disk based on the saveTimeout given to the PersistedAppState widget. By default this value is 500 milliseconds. This timeout is used to stop disk thrashing on multiple map changes in quick succession.

Example

import 'package:flutter/material.dart';
import 'package:state_persistence/state_persistence.dart';

void main() => runApp(App());

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  TextEditingController _textController;

  @override
  Widget build(BuildContext context) {
    return PersistedAppState(
      storage: JsonFileStorage(),
      child: MaterialApp(
        title: 'Persistent TextField Example',
        theme: ThemeData(primarySwatch: Colors.indigo),
        home: Scaffold(
          appBar: AppBar(title: Text('Persistent TextField Example')),
          body: Container(
            padding: const EdgeInsets.all(32.0),
            alignment: Alignment.center,
            child: PersistedStateBuilder(
              builder: (BuildContext context, AsyncSnapshot<PersistedData> snapshot) {
                if (snapshot.hasData) {
                  if (_textController == null) {
                    _textController = TextEditingController(text: snapshot.data['text'] ?? '');
                  }
                  return TextField(
                    controller: _textController,
                    decoration: InputDecoration(
                      hintText: 'Enter some text',
                    ),
                    onChanged: (String value) => snapshot.data['text'] = value,
                  );
                } else {
                  return CircularProgressIndicator();
                }
              },
            ),
          ),
        ),
      ),
    );
  }
}

GitHub

https://github.com/fluttercommunity/state_persistence
You might also like...

Flutter Local Notifications - Learn how to implement local notifications into both Android and iOS using flutter_local_notifications plugin.

Flutter Local Notifications - Learn how to implement local notifications into both Android and iOS using flutter_local_notifications plugin.

Flutter Local Notifications Example Flutter Local Notifications - Learn how to implement local notifications into both Android and iOS using flutter_l

May 15, 2022

A Video and Audio player that can play from local assets, local files and network URLs with the powerful controls

A Video and Audio player that can play from local assets, local files and network URLs with the powerful controls

Video/Audio Player in Flutter with Powerful controls How can we play videos in Flutter? There is a library directly from the Flutter team simply calle

Jan 31, 2022

This repository is Online_Learning Screen UI - Flutter. I am fetching the data from the local JSON API.

online_learning A new Flutter Online_Learning application. Designed by Arun PP, Code with Flutter by Kishor Kc. Kishor Kc I am fetching the data from

Dec 4, 2021

Flutter shareable package of object-oriented classes for local caching of user data in json

Flutter shareable package of object-oriented classes for local caching of user data in json

json_cache Json Cache is an object-oriented package to serve as a layer on top of local storage packages - packages that persist data locally on the u

Jun 17, 2022

Speed Share is a highly available file sharing terminal on LAN(local area network) developed by flutter framework.

Speed Share is a highly available file sharing terminal on LAN(local area network) developed by flutter framework.

速享 Language: 中文简体 | English 这是一款完全基于局域网的文件互传终端,速享不使用任何服务器,不使用您的移动流量,不收集任何用户数据,完全的点对点传输。 可以快速共享文本消息,图片或其他文件,文件夹。 适用于局域网中的文件互传,解决 QQ,微信等上传文件会经过服务器的问题,或者

Jun 25, 2022

Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's information in Flutter.

Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's information in Flutter.

Flutter Tutorial - User Profile & SharedPreferences Let's create a complete Flutter User Profile Page with SharedPreferences to persist the user's inf

Jun 25, 2022

🚰 A BehaviorSubject for Flutter with automatic persist and hydrate

🚰 A BehaviorSubject for Flutter with automatic persist and hydrate

Hydrated Hydrated provides a Subject that automatically persists to Flutter's local storage and hydrates on creation! Easy to consume All values are p

Jan 21, 2022

ToDo App made with flutter which stores your todos based on their categories. The data is stored in external application storage in your device in JSON file.

ToDo App made with flutter which stores your todos based on their categories. The data is stored in external application storage in your device in JSON file.

⭐ My ToDo ⭐ Built with ❤︎ by Akash Debnath This is my second project on Flutter. This app hepls you to keep record of your ToDos. You can create your

May 10, 2022

A simple flutter app that downloads a file from the internet, shows a custom-made download progress dialog and saves the file to device's internal storage

http_downloader A simple flutter app that downloads a file from the internet using the http plugin. It has a custom-designed progress dialog which dis

Apr 6, 2021
Comments
  • 1. Getting this weird error in my app after switching channels or running Flutter upgrade.

    This happened randomly to me once before.. no idea how i Fixed it.. i thought i just did a clean get from GIT and it worked but not sure anymore..

    I have 2 computers / Mac PC. the PC use to have this issue which i randomly fixed.. then a week or so later, the mac started getting it.

    Oddly enough I can take the same code on mac and PC and the Pc currently is working fine in the emulator. but the mac / my iphone XR simulator / iphone SE simulator (all sims) and the Device iPhone 7+ all exhibit the same behavior (coming from the same computer).

    If i make a page that dumps the data, the working side shows tons of data, but on the mac where its broken I get back {} for the data.. any way i can do more debugging or any ideas?

    16:28:35.760 23 info flutter.tools 
    16:28:35.760 24 info flutter.tools  When the exception was thrown, this was the stack:
    16:28:35.761 25 info flutter.tools  #0      _ImmutableMap.[]= (dart:core-patch/immutable_map.dart:74:5)
    16:28:35.761 26 info flutter.tools  #1      PersistedData.[]= (package:state_persistence/state_persistence.dart:142:10)
    16:28:35.761 27 info flutter.tools  #2      _FlashControlPanelState.build.<anonymous closure>.<anonymous closure> (package:qc/flashcards/flashcard_drawer.dart:86:22)
    16:28:35.761 28 info flutter.tools  #3      State.setState (package:flutter/src/widgets/framework.dart:1117:30)
    16:28:35.761 29 info flutter.tools  #4      _FlashControlPanelState.build.<anonymous closure> (package:qc/flashcards/flashcard_drawer.dart:85:15)
    16:28:35.761 30 info flutter.tools  #5      _SliderState._handleChanged (package:flutter/src/material/slider.dart:402:14)
    16:28:35.761 31 info flutter.tools  #6      _RenderSlider._startInteraction (package:flutter/src/material/slider.dart:860:7)
    16:28:35.761 32 info flutter.tools  #7      _RenderSlider._handleDragStart (package:flutter/src/material/slider.dart:890:54)
    16:28:35.761 33 info flutter.tools  #8      DragGestureRecognizer.acceptGesture.<anonymous closure> (package:flutter/src/gestures/monodrag.dart:218:47)
    16:28:35.761 34 info flutter.tools  #9      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24)
    16:28:35.761 35 info flutter.tools  #10     DragGestureRecognizer.acceptGesture (package:flutter/src/gestures/monodrag.dart:218:9)
    16:28:35.761 36 info flutter.tools  #11     _CombiningGestureArenaMember.acceptGesture (package:flutter/src/gestures/team.dart:41:13)
    16:28:35.761 37 info flutter.tools  #12     GestureArenaManager._resolveInFavorOf (package:flutter/src/gestures/arena.dart:263:12)
    16:28:35.761 38 info flutter.tools  #13     GestureArenaManager._resolve (package:flutter/src/gestures/arena.dart:222:9)
    16:28:35.761 39 info flutter.tools  #14     GestureArenaEntry.resolve (package:flutter/src/gestures/arena.dart:52:12)
    16:28:35.761 40 info flutter.tools  #15     _CombiningGestureArenaMember._resolve (package:flutter/src/gestures/team.dart:78:14)
    16:28:35.761 41 info flutter.tools  #16     _CombiningGestureArenaEntry.resolve (package:flutter/src/gestures/team.dart:16:15)
    16:28:35.761 42 info flutter.tools  #17     OneSequenceGestureRecognizer.resolve (package:flutter/src/gestures/recognizer.dart:240:13)
    16:28:35.761 43 info flutter.tools  #18     DragGestureRecognizer.handleEvent (package:flutter/src/gestures/monodrag.dart:193:11)
    16:28:35.761 44 info flutter.tools  #19     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
    16:28:35.761 45 info flutter.tools  #20     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
    16:28:35.761 46 info flutter.tools  #21     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:221:19)
    16:28:35.761 47 info flutter.tools  #22     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22)
    16:28:35.761 48 info flutter.tools  #23     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
    16:28:35.761 49 info flutter.tools  #24     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
    16:28:35.761 50 info flutter.tools  #25     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
    16:28:35.761 51 info flutter.tools  #29     _invoke1 (dart:ui/hooks.dart:233:10)
    16:28:35.762 52 info flutter.tools  #30     _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5)
    16:28:35.762 53 info flutter.tools  (elided 3 frames from package dart:async)
    16:28:35.762 54 info flutter.tools 
    16:28:35.762 55 info flutter.tools  Handler: onStart
    16:28:35.762 56 info flutter.tools  Recognizer:
    16:28:35.762 57 info flutter.tools    HorizontalDragGestureRecognizer#7f4c5(start behavior: start)
    
    Reviewed by zurie at 2019-05-10 20:35
  • 2. Unit testing example?

    A docs improvement I'd find useful is an example of how to test this properly. For some tests I can mock the state_persistence objects. But I want to be sure that old saved data is properly loaded by new code, so for that I want to do round-trip tests with files of data.

    Reviewed by wpietri at 2019-11-22 16:32

Related

Jan 10, 2022
Local data hive - Local data hive for flutter
Local data hive - Local data hive for flutter

local_data_hive A new Flutter application. ScreenShot

Jan 8, 2022
Here is an application project that displays a list of products from the Elevenia API called STORE.
Here is an application project that displays a list of products from the Elevenia API called STORE.

Here is an application project that displays a list of products from the Elevenia API called STORE.

May 18, 2022
Data Migrator - provide a universal translator for data by being portable, diverse, and efficient in migrating and converting data across discrete schemas
Data Migrator - provide a universal translator for data by being portable, diverse, and efficient in migrating and converting data across discrete schemas

Data Migrator - provide a universal translator for data by being portable, diverse, and efficient in migrating and converting data across discrete schemas

Jun 18, 2022
A demonstration of using Riverpod for dynamic locale switching in-app, with persistence.
A demonstration of using Riverpod for dynamic locale switching in-app, with persistence.

Riverpod Localization A demonstration of using Riverpod for dynamic locale switching in-app, with persistence. How It Works Fallback Locale: Declared

Jun 23, 2022
Small Flutter app that uses SQLite to persist data.

Crud_With_Flutter_And_Sqlite A new Flutter project. The application allows you to register a user with your name and email, edit and also delete. All

Jun 11, 2022
Automatically generate profile picture with random first name and background color. But you can still provide pictures if you have them. As the default color, based on the name of the first letter. :fire: :fire: :fire:
Automatically generate profile picture with random first name and background color. But you can still provide pictures if you have them. As the default color, based on the name of the first letter. :fire: :fire: :fire:

FLUTTER PROFILE PICTURE Automatically generate profile picture with random first name and background color. But you can still provide pictures if you

May 3, 2022
Add beautiful and trending tab indicators directly to your default Flutter TabBar
Add beautiful and trending tab indicators directly to your default Flutter TabBar

Add beautiful and trending tab indicators directly to your default Flutter TabBar. Features ?? Supports Android, iOS, Web Can be directly added to the

Jun 28, 2022
A replacement for Flutter's default SafeArea widget
A replacement for Flutter's default SafeArea widget

ColorfulSafeArea A more customizable replacement for the SafeArea widget. It lets you set the color of your SafeArea without affecting the color of it

Jun 18, 2022
Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web.
Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web.

Flutter Tutorial - Hive NoSQL Database Persist data with Flutter's Hive NoSQL Database locally on Android, iOS & Web. ✌  Preview App Preview Course Pr

Jun 15, 2022