rx_shared_preference 1.0.1

rx_shared_preference alt text

Author: Petrus Nguyễn Thái Học

Codacy Badge Pub Build Status License: MIT

  • Shared preference with RxDart Stream observation.
  • Reactive shared preferences for Flutter.
  • Reactive stream wrapper around SharedPreferences.
  • This package provides reactive shared preferences interaction with very little code. It is designed specifically to be used with Flutter and Dart.

More detail about return Observable

  • Observable will emit the initial value as its first next event (Emit value as soon as possible after is listen to) (emit null when value is not set)
  • It will automatic emit value when value associated with key was changed successfully (emit null when value associated with key was removed or set to null)
  • When read value is not valid type (wrong type):
    • Will emit error if value is present (not null)
    • Emit null when value is absent (value is not set, value is null) (because null can be cast to any type).
  • Can emit two consecutive data events that are equal. You should use Rx operator like distinct (More commonly known as distinctUntilChanged in other Rx implementations) to create an Observable where data events are skipped if they are equal to the previous data event.

Getting Started #

In your flutter project, add the dependency to your pubspec.yaml

dependencies:
  ...
  rx_shared_preference: <latest_version>

Usage #

Import rx_shared_preference and shared_preferences

import 'package:rx_shared_preference/rx_shared_preference.dart';
import 'package:shared_preferences/shared_preferences.dart';

Wrap your SharedPreferences in a RxSharedPreferences.

final rxSharedPreferences = RxSharedPreferences(
  await SharedPreferences.getInstance()
);

or not need keyword await before SharedPreferences.getInstance()

final rxSharedPreferences = RxSharedPreferences(
  SharedPreferences.getInstance()
);

You can add logger optional parameter to RxSharedPreferences constructor. Logger will log messages about operations (such as read, write) and observable values

final rxSharedPreferences = RxSharedPreferences(
  SharedPreferences.getInstance(),
  (message) => print('[RX_SHARED_PREF] :: $message'),
);

or simply pass print function to RxSharedPreferences constructor

final rxSharedPreferences = RxSharedPreferences(
  SharedPreferences.getInstance(),
  print,
);

And then, just listen Observable, transform Observable through operators such as (map, flatMap, etc...). If you need listen to this Observable many times, you can use broadcast operators such as share, shareValue, publish, publishValue, ...

rxSharedPreferences.getStringListObservable('KEY').listen(print);

rxSharedPreferences.getStringListObservable('KEY').share();
rxSharedPreferences.getStringListObservable('KEY').shareValue();

rxSharedPreferences.getIntObservable('KEY')
  .map((i) => /*Do something cool*/)
  ...
  ...

RxSharedPreferences is like to SharedPreferences, it provides read write functions: getBool, getDouble, getInt, ..., setBool, setDouble, setInt, etc...

Example demo: #

Build ListView from Stream using RxSharedPreferences #

DemoCode

Change theme runtime: #

https://github.com/hoc081098/flutter-change-theme-youtube-code

License #

MIT License

Copyright (c) 2019 Petrus Nguyễn Thái Học

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

[1.0.1] - April 28, 2019

  • Update dependencies (rxdart and shared_preferences) to latest version

  • Add reload method

  • Some minor changes

[1.0.0+2] - April 28, 2019

  • Update README.md

[1.0.0+1] - April 27, 2019

  • Add test

[1.0.0] - April 15, 2019

  • Refactor and add comment for public API.
  • Add example.

[0.0.9] - April 14, 2019

  • Initial

example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:rx_shared_preference/rx_shared_preference.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:rxdart/rxdart.dart';

void main() {
  final rxSharedPreferences = RxSharedPreferences(
    SharedPreferences.getInstance(),
    (message) => print('[RX_SHARED_PREF] :: $message'),
  );
  runApp(MyApp(rxSharedPreferences));
}

class MyApp extends StatelessWidget {
  final RxSharedPreferences rxSharedPreferences;

  const MyApp(this.rxSharedPreferences);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Rx Shared Preference example',
      theme: ThemeData.dark(),
      home: MyHomePage(rxSharedPreferences),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final RxSharedPreferences rxSharedPreferences;

  const MyHomePage(this.rxSharedPreferences);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const _key = 'com.hoc.list';

  final _scaffoldKey = GlobalKey<ScaffoldState>();
  final _textEditingController = TextEditingController();

  RxSharedPreferences _rxSharedPreferences;
  ValueObservable<List<String>> _list$;
  StreamSubscription<List<String>> _subscription;

  @override
  void initState() {
    super.initState();
    _rxSharedPreferences = widget.rxSharedPreferences;
    _initStream();
  }

  void _initStream() {
    final list$ =
        _rxSharedPreferences.getStringListObservable(_key).publishValue();
    _subscription = list$.connect();
    _list$ = list$;
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: StreamBuilder<List<String>>(
        stream: _list$,
        initialData: _list$.value,
        builder: (context, snapshot) {
          final list = snapshot.data ?? <String>[];
          return ListView.builder(
            itemCount: list.length,
            physics: BouncingScrollPhysics(),
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(list[index]),
                trailing: IconButton(
                    icon: Icon(Icons.remove_circle),
                    onPressed: () => _removeString(list[index])),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addString,
        child: Icon(Icons.add),
        tooltip: 'Add string',
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }

  void _addString() async {
    _textEditingController.text = '';
    final string = await showDialog<String>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('Add a string'),
          content: TextField(
            autofocus: true,
            keyboardType: TextInputType.text,
            textInputAction: TextInputAction.done,
            controller: _textEditingController,
            onSubmitted: (s) {
              print('Submit $s');
              Navigator.of(context).pop(s);
            },
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('OK'),
              onPressed: () {
                print('OK ${_textEditingController.text}');
                Navigator.of(context).pop(_textEditingController.text);
              },
            ),
          ],
        );
      },
    );
    if (string != null) {
      final currentList =
          await _rxSharedPreferences.getStringList(_key) ?? <String>[];
      final newList = List.of(currentList)..add(string);
      final result = await _rxSharedPreferences.setStringList(
        _key,
        newList,
      );
      _scaffoldKey.currentState?.showSnackBar(
        SnackBar(
          content: Text(
            result
                ? "Add '$string' successfully"
                : "Add '$string' not successfully",
          ),
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }

  void _removeString(String needRemove) async {
    final remove = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('Remove this string'),
          actions: <Widget>[
            FlatButton(
              child: Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop(false);
              },
            ),
            FlatButton(
              child: Text('OK'),
              onPressed: () {
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );
    if (remove ?? false) {
      final currentList =
          await _rxSharedPreferences.getStringList(_key) ?? <String>[];
      final newList = List.of(currentList)..remove(needRemove);
      final result = await _rxSharedPreferences.setStringList(
        _key,
        newList,
      );
      _scaffoldKey.currentState?.showSnackBar(
        SnackBar(
          content: Text(
            result
                ? "Remove '$needRemove' successfully"
                : "Remove '$needRemove' not successfully",
          ),
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  rx_shared_preference: ^1.0.1

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:rx_shared_preference/rx_shared_preference.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
62
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
81
Learn more about scoring.

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

  • Dart: 2.4.0
  • pana: 0.12.19
  • Flutter: 1.7.8+hotfix.3

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Fix lib/src/rx_shared_preference.dart. (-0.50 points)

Analysis of lib/src/rx_shared_preference.dart reported 1 hint:

line 160 col 42: This function has a return type of 'Future

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
rxdart ^0.22.0 0.22.1
shared_preferences ^0.5.3+1 0.5.3+4
Transitive dependencies
collection 1.14.11
meta 1.1.6 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
test_api ^0.2.4

Admin