Flutter Tutorial – Shared Preferences (Android and iOS)

By | January 29, 2019

This article shows how to implement Shared Preferences in Flutter.
 
Watch Video Tutorial
 

 
Add Dependency
 
We will be using the shared_preferences plugin from Flutter to implement this.
 
You can go to this link and read more about it.
 
Go to your pubspec.yaml file and add the dependency.
 

 dependencies:
  flutter:
    sdk: flutter

  // your other dependencies..
  shared_preferences: ^0.5.0
  ...

 
Import plugins
 
Import the library to the project file you need. You may need to import the ‘services’ package from flutter because shared preferences uses async operations,
 

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

 
Save Data to Preferences
 

Future<bool> saveData() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return await preferences.setString('your_key", "your_data");
}

 
Get the data from Preferences
 

Future<string> loadData() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return preferences.getString("your_key");
}

 
Set the Data to your variable
 
I am declaring a variable ‘data’ and getting the saved data from preferences to the ‘data’ variable with the below function.
 

 setData() {
    loadData().then((value) {
      setState(() {
        data = value;
      });
    });
 }

 
Test Shared Preferences
 
If you want to test preferences by loading some data prior to user saving some data, you can do that with the below code.
 
I am going that in the initState function and calling setData function at the end to show the initial value.
 

@override
  void initState() {
    super.initState();
    const MethodChannel('plugins.flutter.io/shared_preferences')
        .setMockMethodCallHandler(
      (MethodCall methodcall) async {
        if (methodcall.method == 'getAll') {
          return {"flutter." + nameKey: "[ No Name Saved ]"};
        }
        return null;
      },
    );
    setData();
  }
  ...
 

setMockMethodCallHandler is used for testing purposes normally.

 
Complete Example
 
Here I have a TextField, a save button, a Text and another button in the UI. The first button calls ‘saveData’ function to save the data from the TextField to the preferences and second button calls ‘setData’ function which loads te data to our variable and set it to the Text Widget.
 
So here is the complete code
 

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

class SharedPreferenceDemo extends StatefulWidget {
  SharedPreferenceDemo() : super();

  final String title = "Shared Preference Demo";

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

class SharedPreferenceDemoState extends State<SharedPreferenceDemo> {
  //
  String data = "";
  String nameKey = "_key_name";
  TextEditingController controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    const MethodChannel('plugins.flutter.io/shared_preferences')
        .setMockMethodCallHandler(
      (MethodCall methodcall) async {
        if (methodcall.method == 'getAll') {
          return {"flutter." + nameKey: "[ No Name Saved ]"};
        }
        return null;
      },
    );
    setData();
  }

  Future<bool> saveData() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return await preferences.setString(nameKey, controller.text);
  }

  Future<String> loadData() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    return preferences.getString(nameKey);
  }

  setData() {
    loadData().then((value) {
      setState(() {
        data = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(30.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            TextField(
              controller: controller,
              decoration: InputDecoration.collapsed(hintText: "Enter Name"),
            ),
            OutlineButton(
              child: Text("SAVE NAME"),
              onPressed: () {
                saveData();
              },
            ),
            Text(
              data,
              style: TextStyle(fontSize: 20),
            ),
            OutlineButton(
              child: Text("LOAD NAME"),
              onPressed: () {
                setData();
              },
            ),
          ],
        ),
      ),
    );
  }
}

 
That’s it. You can watch the complete youtube tutorial above for better understanding.
 
 

Leave a Reply

Your email address will not be published. Required fields are marked *