Categories
Uncategorized

Using shared preferences

In your app you often need to give users the ability to customize and save app settings .

In platforms like phonegap or cordova we typically store these settings inside browser localStorage

In flutter we can save user customizations on the device using a plugin such as shared_preferences.

Preferences are simple key value pairs. Storing critical data inside shared preferences is not recommended.

To add shared preferences your app, add the package name to your pubspec.yaml file


Once you save pubspec.yaml the package should be installed or you can run “flutter pub get” from the command line inside your projects

Next import shared_preferences.dart inside your app and start using shared preferences once initialized

Get reference to shared preference

Before you can start saving preferences you need to get a reference to SharedPreferences by calling SharedPreferences.getInstance()

This is an async operation and returns a Future

Once we have a reference we can functions to get and set values in SharedPrerences

Future<SharedPreferences> _sprefs = SharedPreferences.getInstance(

Add preference

Once we have a shared preferences object we can start adding data by calling a set function. Set functions are available for bool, int, double, string and string lists

  • _sprefs.setString(“key”, “value”)
  • _sprefs.setInt(“age”, 10)
  • _sprefs.setDouble(“temperature”, 20.5)
  • _sprefs.setBool(“key”,true)
  • _sprefs.setStringList(“key”, List<String>)

Get Preference

To get a specific preference use a get function

  • _sprefs.getString(“keyname”)
  • _sprefs.getDouble(“keyname”)
  • _sprefs.getBool(“keyname”)
  • _sprefs.getInt(“keyname”)

Load preferences

Prefences can be loaded on startup and made available to the application.

 //read peferences
  Future<String> loadPrefs() async {
    final SharedPreferences prefs = await _sprefs;
    return prefs.getString("fruit");
  }

Remove preference

To remove a preference use the remove function

_sprefs.remove("key")

Here is a simple app showing how to create and update preferences and how to load preferences on startup

import 'package:flutter/material.dart';
import 'dart:async' show Future;
import 'package:shared_preferences/shared_preferences.dart';

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

class MyEx extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Preferences sample app',
      home: MyApp(),
    );
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String prefData;

  TextEditingController preferenceController = TextEditingController();
  Future<SharedPreferences> _sprefs = SharedPreferences.getInstance();

  //read peferences
  Future<String> loadPrefs() async {
    final SharedPreferences prefs = await _sprefs;
    return prefs.getString("fruit");
  }

  @override
  void initState() {
    loadPrefs().then((data) {
      setState(() {
        if (data == null) {
          //prerence does not exist
          prefData = "Choose your favorite fruit.";
        } else {
          // found preference
          prefData = data;
        }
      });
    });

    super.initState();
  }

  //restart app to verify changes
  void updatePreference() async {
    SharedPreferences myPrefs = await SharedPreferences.getInstance();
    setState(() {
      if (preferenceController.text.length > 0) {
        prefData = preferenceController.text;
        myPrefs.setString("fruit", prefData);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //app bar
      body: Container(
        padding: EdgeInsets.all(40.0),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                "Favorite Fruit",
                style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text("$prefData"),
              SizedBox(
                width: 20.0,
              ),
              TextField(
                controller: preferenceController,
              ),
              SizedBox(
                width: 20.0,
              ),
              RaisedButton(
                child: Text("Update Fruit"),
                onPressed: updatePreference,
              )
            ],
          ),
        ),
      ),
    );
  }
}

Code

You can download the code here

If you find this article useful, please consider sharing it and also giving the repo a star on github.

Sign up to be notified of new posts. I promise i won’t spam you.