SharedPreferences for Flutter data storage

When we do APP development, we often involve the storage of user data (such as the storage of user login token and some user preference Settings, etc.). Those of you who have developed Android should know that SharedPreferences are available. Flutter also provides us with a very similar (even named) component that provides us with data storage capabilities.

This tutorial will use a simple little Demo to fully master the use of SharedPreferences for data storage.

If the picture displays abnormally, please visit my official blog

The effect

With the picture and the truth, let’s take a look at our final result:

The warehouse address

All source code (with comments) has been uploaded to the open source repository:

  • Github
  • Yards cloud

The preparatory work

The development environment

Environment overview of this blog:

The environment The version number
Flutter 1.14.6 beta
Dart 2.8.0 – dev. 5.0
Android Studio 3.5.2

Pay attention to your environment and the differences in the text, to avoid incompatible situations oh!

Required conditions

To navigate this article, assume that you already have the following conditions:

  1. A computer (can run IDE and APP emulator at the same time).
  2. Android StudioVSCode(or whatever code editor you like).
  3. FlutterDevelopment environment.
  4. You have masteredFlutterAt least understand the directory structure,DartBasic language knowledge).

Actual combat began

Create the Flutter Project

Create a new Flutter project named my_shared_preferences_demo(you can name it however you like, but replace it with your own name below).

Note: the name of the Flutter project should not be the same as that of an introduced third-party library. Otherwise, A package may not list itself as A dependency

Code screenshot:

Clean up the code

Because our project is too simple, we don’t need to test it for now. Delete./test directory:

To avoid redundant code misleading us, replace./lib/main.dart with:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SharedPreferences Demo',
      home: MyHomePage(title: 'SharedPreferences Demo Page')); }}class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    returnScaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[], ), ), ); }}Copy the code

Import the SharedPreferences third-party library

Go to./pubspec.yaml and add dependencies:

dependencies:
  shared_preferences: ^ 0.5.6 + 3
Copy the code

You can also check out the latest Shared_Preferences on the official website

Screenshots:

Update package, enter in terminal (or click the IDE update package button):

flutter packages get
Copy the code

Operating Projects:

Now we are ready to store the data!

Create data read and write utility classes

In a real project, we will need to read and write data many times, so it is wise to encapsulate a utility class.

Create. / lib/shared_preferences_util. Dart

createSharedPreferencesUtilclass

class SharedPreferencesUtil {}Copy the code

Import shared_preferences because you need SharedPreferences later:

import 'package:shared_preferences/shared_preferences.dart';
Copy the code

Data storage functionsaveData()

Add function saveData():

  // save the data
  static saveData<T>(String key, T value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    switch (T) {
      case String:
        prefs.setString(key, value as String);
        break;
      case int:
        prefs.setInt(key, value as int);
        break;
      case bool:
        prefs.setBool(key, value as bool);
        break;
      case double:
        prefs.setDouble(key, value as double);
        break; }}Copy the code

When defining functions, there is an extra ”

” after the name, which makes use of generics. If in doubt, do your own search for “DART generics.”

Key is the “name” of the value we want to store. This name is unique, and we need to pass in the corresponding key. value when we read the data later. Inside the function, we introduce an instance of SharedPreferences in the first line for later use. The switch branch is used to determine the generic type passed in. After the judgment is complete, call prefs.setxxx (key, value) to complete the data storage.

Code screenshot:

Data reading functiongetData()

If there is a data store function, there should be a corresponding data read function. Let’s write:

Add function getData():

  /// read data
  static Future<T> getData<T>(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    T res;
    switch (T) {
      case String:
        res = prefs.getString(key) as T;
        break;
      case int:
        res = prefs.getInt(key) as T;
        break;
      case bool:
        res = prefs.getBool(key) as T;
        break;
      case double:
        res = prefs.getDouble(key) as T;
        break;
    }
    return res;
  }
Copy the code

Code parsing: Similar to the saveData() function above, it uses generics and switch. Prefs.getxxx () is called to read the data.

Code screenshot:

At this point, we are almost done with our tutorial. Those of you who are quick should be ready to use it. But emirates’ tutorials need to be complete so that everyone can use them and understand why. Let’s draw the APP interface, more intuitive test!

Draws a simple interface for testing tool classes

Dart back to.lib /main.dart, let’s add some buttons and input fields.

The importSharedPreferencesUtil

Import SharedPreferencesUtil for subsequent use:

import 'package:my_shared_preferences_demo/shared_preferences_util.dart';
Copy the code

Defining instance variables

Define instance variables _savedValue and _currentInputValue in _MyHomePageState to record the store and the currently entered value:

  // The saved value
  String _savedValue = "Loading...";

  // The current input value
  String _currentInputValue;
Copy the code

Load the data when the page is initialized.

Define initState() to read the existing data when the page is initialized

  @override
  void initState() {
    super.initState();
    SharedPreferencesUtil.getData<String> ("myData").then((value) {
      setState(() {
        _savedValue = value;
      });
    });
  }
Copy the code

Code parsing: You can see @override on initState() because initState() is an inherited function. Super.initstate () is called internally. The next step is to retrieve the stored data using the SharedPreferencesUtil defined earlier. Since shared_Preferences provides functions that are async, it needs to use.then() to ensure that it gets the data before doing anything else. After obtaining value, save it to _savedValue.

In build->Scaffold->body:Center-> Child: Column->children, add the following code blocks:

            // Text for displaying data
            Text(
              _savedValue == null ? "No data" : _savedValue,
              style: TextStyle(fontSize: 60, fontWeight: FontWeight.bold),
            ),
            // Input box for modifying data
            TextField(
              onChanged: (value) {
                _currentInputValue = value;
              },
              // Add a border to the input box just for aesthetics
              decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(10.0),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(15.0),
                  )),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                // Trigger the button to save data
                RaisedButton(
                  child: Text("Save"),
                  onPressed: () {
                    // When the button is clicked, the function that stores the data is called
                    SharedPreferencesUtil.saveData<String> ("myData", _currentInputValue);

                    // Render the currently displayed saved value
                    setState(() {
                      _savedValue = _currentInputValue;
                    });
                  },
                ),
                RaisedButton(
                  child: Text("Clear data"),
                  onPressed: () {
                    // When the button is clicked, the function that stores the data is called
                    SharedPreferencesUtil.saveData<String> ("myData".null);

                    // Render the currently displayed saved value
                    setState(() {
                      _savedValue = "No data"; }); },)],),Copy the code

Code parsing: Although it looks a bit more code, there is essentially only 1 input box and 2 buttons. There is no particularly complicated logic, all instructions are in the code comments, you can view.

The above code screenshot:

You’re done

If your code is fine and you run the project, it should look like this:

Through the above steps, we finally complete the SharedPreference of Flutter data store. Isn’t it easy?

The warehouse address

All source code (with comments) has been uploaded to the open source repository:

  • Github
  • Yards cloud

If you have any questions, objections or suggestions for improvement, please feel free to comment below. The author will reply asap! If the picture is not displayed properly, please read the official blog.

For more and better tutorials/blogs/information, please visit my official website: Emirates Technical website.