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

Overview

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();
                }
              },
            ),
          ),
        ),
      ),
    );
  }
}
You might also like...

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

Oct 6, 2022

🌈 Repository for a compass project, basically an App for displaying bank transfers, with API requests, Flag persistence, Infinite Scroll, Error Handling, Unit Tests, Extract Sharing working with SOLID, BLoC and Designer Patterns.

🌈 Repository for a compass project, basically an App for displaying bank transfers, with API requests, Flag persistence, Infinite Scroll, Error Handling, Unit Tests, Extract Sharing working with SOLID, BLoC and Designer Patterns.

💸 Green Bank Aplicação desenvolvida em Flutter com intuito de trabalhar conexão com API, Gerenciamento de estado usando BLoC, Refatoração, Arquitetur

Oct 7, 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

Dec 20, 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

Dec 23, 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

Nov 11, 2022

Advanced & beautiful animations inspired by animate_do and Animate.css, every animation is a widget that contains default but customizable values 💙

Advanced & beautiful animations inspired by animate_do and Animate.css, every animation is a widget that contains default but customizable values 💙

animate_it An animation package inspired by animate_do and Animate.css. Since the original animate_do is not being maintained, I have decided to creat

Oct 1, 2022

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

Nov 29, 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

Jul 5, 2022
Comments
  • Getting this weird error in my app after switching channels or running Flutter upgrade.

    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)
    
    bug 
    opened by zurie 2
  • Unit testing example?

    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.

    opened by wpietri 0
Owner
Flutter Community
A central place for all community made Flutter packages. To get started, see the README of the 'community' repository.
Flutter Community
Seyifunmi Araoluwa 1 Jan 10, 2022
[Flutter package] An easy and quick way to check if the local app is updated with the same version in their respective stores (Play Store / Apple Store ).

Retrieve version and url for local app update against store app Android and iOS Features Using as reference packages like in_app_update , version_chec

Kauê Murakami 11 Nov 9, 2022
Local data hive - Local data hive for flutter

local_data_hive A new Flutter application. ScreenShot

Mehmet Emre ÖZ 0 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.

Dedi Kurniawan 2 May 18, 2022
A CLI tool and Dart package that can scrape file and directory URLs from h5ai instances.

h5ai scraper A CLI tool and Dart package that can scrape file and directory URLs from h5ai instances. Usage This tool requires the Dart SDK. It can be

null 1 Jan 4, 2023
Serialize almost everything you ever need! 📦 Supports serializing MaterialColor, Color, Size, Locale, IconData, UuidValue, DateTime, Directory, File, Duration, and many more.

osum_serializable The goal is to serialize almost everything you ever need! json_serializable is an amazing package to serialize classes but cannot se

Aswin Murali 2 Sep 23, 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

Tanner Meade 77 Jan 2, 2023
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

Idelfonso Joás 0 Oct 22, 2022
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

Johannes Milke 54 Dec 31, 2022