shared_preferences 0.4.1

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

Shared preferences plugin

pub package

Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing a persistent store for simple data. Data is persisted to disk asynchronously. Neither platform can guarantee that writes will be persisted to disk after returning and this plugin must not be used for storing critical data.

Usage

To use this plugin, add shared_preferences as a dependency in your pubspec.yaml file.

Example

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

void main() {
  runApp(new MaterialApp(
    home: new Scaffold(
      body: new Center(
      child: new RaisedButton(
        onPressed: _incrementCounter,
        child: new Text('Increment Counter'),
        ),
      ),
    ),
  ));
}

_incrementCounter() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int counter = (prefs.getInt('counter') ?? 0) + 1;
  print('Pressed $counter times.');
  await prefs.setInt('counter', counter);
}

Testing

You can populate SharedPreferences with initial values in your tests by running this code:

const MethodChannel('plugins.flutter.io/shared_preferences')
  .setMockMethodCallHandler((MethodCall methodCall) async {
    if (methodCall.method == 'getAll') {
      return <String, dynamic>{}; // set initial values here if desired
    }
    return null;
  });

0.4.1

  • Added getKeys method.

0.4.0

  • Breaking change. Set SDK constraints to match the Flutter beta release.

0.3.3

  • Fixed Dart 2 issues.

0.3.2

  • Added an getter that can retrieve values of any type

0.3.1

  • Simplified and upgraded Android project template to Android SDK 27.
  • Updated package description.

0.3.0

  • Breaking change. Upgraded to Gradle 4.1 and Android Studio Gradle plugin 3.0.1. Older Flutter projects need to upgrade their Gradle setup as well in order to use this version of the plugin. Instructions can be found here.

0.2.6

  • Added FLT prefix to iOS types

0.2.5+1

  • Aligned author name with rest of repo.

0.2.5

  • Fixed crashes when setting null values. They now cause the key to be removed.
  • Added remove() method

0.2.4+1

  • Fixed typo in changelog

0.2.4

  • Added setMockInitialValues
  • Added a test
  • Updated README

0.2.3

  • Suppress warning about unchecked operations when compiling for Android

0.2.2

  • BREAKING CHANGE: setStringSet API changed to setStringList and plugin now supports ordered storage.

0.2.1

  • Support arbitrary length integers for setInt.

0.2.0+1

  • Updated README

0.2.0

0.1.1

  • Upgrade Android SDK Build Tools to 25.0.3.

0.1.0

  • Initial Open Source release.

example/lib/main.dart

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

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

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'SharedPreferences Demo',
      home: new SharedPreferencesDemo(),
    );
  }
}

class SharedPreferencesDemo extends StatefulWidget {
  SharedPreferencesDemo({Key key}) : super(key: key);

  @override
  SharedPreferencesDemoState createState() => new SharedPreferencesDemoState();
}

class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  Future<int> _counter;

  Future<Null> _incrementCounter() async {
    final SharedPreferences prefs = await _prefs;
    final int counter = (prefs.getInt('counter') ?? 0) + 1;

    setState(() {
      _counter = prefs.setInt("counter", counter).then((bool success) {
        return counter;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _counter = _prefs.then((SharedPreferences prefs) {
      return (prefs.getInt('counter') ?? 0);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: const Text("SharedPreferences Demo"),
      ),
      body: new Center(
          child: new FutureBuilder<int>(
              future: _counter,
              builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return const CircularProgressIndicator();
                  default:
                    if (snapshot.hasError)
                      return new Text('Error: ${snapshot.error}');
                    else
                      return new Text(
                        'Button tapped ${snapshot.data} time${ snapshot.data == 1 ? '' : 's' }.\n\n'
                            'This should persist across restarts.',
                      );
                }
              })),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: new Icon(Icons.add),
      ),
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  shared_preferences: ^0.4.1

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:shared_preferences/shared_preferences.dart';
  
Version Uploaded Documentation Archive
0.4.2 Jun 1, 2018 Go to the documentation of shared_preferences 0.4.2 Download shared_preferences 0.4.2 archive
0.4.1 Apr 9, 2018 Go to the documentation of shared_preferences 0.4.1 Download shared_preferences 0.4.1 archive
0.4.0 Mar 9, 2018 Go to the documentation of shared_preferences 0.4.0 Download shared_preferences 0.4.0 archive
0.3.3 Feb 28, 2018 Go to the documentation of shared_preferences 0.3.3 Download shared_preferences 0.3.3 archive
0.3.2 Feb 5, 2018 Go to the documentation of shared_preferences 0.3.2 Download shared_preferences 0.3.2 archive
0.3.1 Jan 12, 2018 Go to the documentation of shared_preferences 0.3.1 Download shared_preferences 0.3.1 archive
0.3.0 Dec 20, 2017 Go to the documentation of shared_preferences 0.3.0 Download shared_preferences 0.3.0 archive
0.2.5 Aug 30, 2017 Go to the documentation of shared_preferences 0.2.5 Download shared_preferences 0.2.5 archive
0.2.4+1 Jun 5, 2017 Go to the documentation of shared_preferences 0.2.4+1 Download shared_preferences 0.2.4+1 archive
0.2.4 Jun 5, 2017 Go to the documentation of shared_preferences 0.2.4 Download shared_preferences 0.2.4 archive

All 14 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
100
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]
100
Learn more about scoring.

We analyzed this package on Sep 18, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.3
  • Flutter: 0.8.4

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
flutter 0.0.0
meta ^1.0.4 1.1.6
Transitive dependencies
collection 1.14.11
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test