rx_shared_preference 1.0.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new54

rx_shared_preference #

Pub

Shared preference with RxDart Stream observation. Reactive shared preferences for Flutter. Reactive stream wrapper around SharedPreferences.

Getting Started #

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

dependencies:
  ...
  rx_shared_preference: ^1.0.0

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...

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.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.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages 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';
  
Version Uploaded Documentation Archive
1.0.0 Apr 15, 2019 Go to the documentation of rx_shared_preference 1.0.0 Download rx_shared_preference 1.0.0 archive
0.0.9 Apr 14, 2019 Go to the documentation of rx_shared_preference 0.0.9 Download rx_shared_preference 0.0.9 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
9
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]
54
Learn more about scoring.

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

  • Dart: 2.2.0
  • pana: 0.12.14
  • Flutter: 1.4.7

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/rx_shared_preference.dart.

Run flutter format to format lib/rx_shared_preference.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
rxdart ^0.21.0 0.21.0
shared_preferences ^0.5.2 0.5.2
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