state_persistence 0.0.7

  • Readme
  • Changelog
  • Example
  • Installing
  • 84

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();
                }
              },
            ),
          ),
        ),
      ),
    );
  }
}

Changelog #

0.0.7 #

  • Add clearDataOnLoadError feature.
  • Improve error logging.

0.0.6 #

  • Revert path dependency to 1.6.2

0.0.5 #

  • Added Flutter Community banner.

0.0.4 #

  • Fixed bug with unmodifiable initial data.

0.0.3 #

  • Added support for Initial Data.

0.0.2 #

  • Minor pub suggested improvements.

0.0.1 #

  • Initial version

example/lib/example.dart

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

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return PersistedAppState(
      storage: JsonFileStorage(initialData: {
        'tab': 1,
      }),
      child: MaterialApp(
        title: 'Persistent Tab Example',
        theme: ThemeData(primarySwatch: Colors.blue),
        home: ExampleScreen1(),
      ),
    );
  }
}

class ExampleScreen1 extends StatefulWidget {
  @override
  _ExampleScreen1State createState() => _ExampleScreen1State();
}

class _ExampleScreen1State extends State<ExampleScreen1> with SingleTickerProviderStateMixin {
  PersistedData _data;
  TabController _controller;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _data = PersistedAppState.of(context);
    if (_data != null && _controller == null) {
      _controller = TabController(initialIndex: _data['tab'] ?? 0, vsync: this, length: 4);
      _controller.addListener(_onTabChanged);
    }
  }

  void _onTabChanged() {
    if (!_controller.indexIsChanging) {
      _data['tab'] = _controller.index;
    }
  }

  @override
  void dispose() {
    _controller?.removeListener(_onTabChanged);
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_data != null) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Persistent Tab Example'),
          bottom: TabBar(
            controller: _controller,
            tabs: [
              Tab(text: 'First'),
              Tab(text: 'Second'),
              Tab(text: 'Third'),
              Tab(text: 'Forth'),
            ],
          ),
        ),
        body: TabBarView(
          controller: _controller,
          children: [
            Center(child: Text('Tab 1')),
            Center(child: Text('Tab 2')),
            Center(child: Text('Tab 3')),
            Center(child: Text('Tab 4')),
          ],
        ),
      );
    } else {
      return Center(child: CircularProgressIndicator());
    }
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  state_persistence: ^0.0.7

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:state_persistence/state_persistence.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
72
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
84
Learn more about scoring.

We analyzed this package on Nov 15, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.0
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.6

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/state_persistence.dart.

Run flutter format to format lib/state_persistence.dart.

Maintenance suggestions

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
path ^1.6.2 1.6.4
path_provider ^1.2.0 1.4.2
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.7 1.1.8
platform 2.2.1
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test