Flutter data storage shared_preferences

Preface

Anyone who has done android development knows that you can use SharedPreferences, a lightweight storage class to store key-value pair information. In Flutter, we can use the shared_preferences library to support both Android and ios platforms.

Reference:
1. "Local Storage in Flutter"

  1. "Flutter Knowledge Points: SharedPreferences for Data Storage"

  2. shared_preferences 0.4.2

Use introduction

  1. pubspec.yamlAdd dependencies in the file

 

shared_preferences: "^0.4.2"

The added position is shown in the figure:

 

Add dependency

  1. Install dependent libraries
    Execute $ flutter packages getcommand

  2. Import the library in the corresponding file

 

import 'package:shared_preferences/shared_preferences.dart';
  1. CRUD
    by:

 

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(key, value)
prefs.setBool(key, value)
prefs.setDouble(key, value)
prefs.setInt(key, value)
prefs.setStringList(key, value)

The key is the name you store, and the value is the value you store.
Delete:

 

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key); //删除指定键
prefs.clear();//清空键值对

change:

Change and increase are the same, only need to execute the setXXX() method again to overwrite the previous data.

check:

 

Several APIs for query operations

Usage example

image.png

 

First, we created a TextField to get user input, and then we defined a button below. Whenever the button is stored immediately, the save() method is triggered, and every time the get button is clicked, the get() method is triggered.
Let's take a look at the save() method first

 

save() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(mUserName, _userNameController.value.text.toString());
}

In the save method above, we can see that we have added async and await keywords to it, because the storage of SharedPreferences is also a lightweight and time-consuming operation, so we also need to do it asynchronously.
We use the SharedPreferences.getInstance() method to instantiate the SharedPreferences object, and use its setString method to store the string entered by the user.

 

setString(key, value)

Next look at the get method

 

Future<String> get() async {
  var userName;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userName = await prefs.getString(mUserName);
  return userName;
}

In the get method, we also instantiate a SharedPreferences object, and call the getString method of SharedPreferences to get the object we stored.
getString(key)
The key is the value we just saved, we can use this value to find the object we saved locally and return it.
Similarly, the get method is also a time-consuming operation and also requires asynchronous execution. We use async and await to make the get method asynchronous and return a Future object whose generic type is String.

 

Future<String> userName = get();
                         userName.then((String userName) {
                           Scaffold.of(context).showSnackBar(
                                SnackBar(content: Text("数据获取成功:$userName")));
                         });

We use the obtained Future object to call the then() method. When the get method is executed, the operation in the then() method will be automatically triggered to pop up showSnackBar.
The complete code is given below:

 

import 'dart:async';

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

void main() {
  runApp(new MaterialApp(home: new MyApp()));
}



class MyApp extends StatelessWidget {
  final String mUserName = "userName";
  final _userNameController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    save() async{
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString(mUserName, _userNameController.value.text.toString());
    }

    Future<String> get() async {
      var userName;

        SharedPreferences prefs = await SharedPreferences.getInstance();
         userName = prefs.getString(mUserName);
      return userName;
    }

    return new Builder(builder: (BuildContext context) {
      return new Scaffold(
        appBar:  AppBar(
          title:  Text("SharedPreferences"),
        ),
        body:  Center(
          child: new Builder(builder: (BuildContext context){
            return
                Column(
                  children: <Widget>[
                     TextField(
                      controller: _userNameController,
                      decoration:  InputDecoration(
                          contentPadding: const EdgeInsets.only(top: 10.0),
                          icon:  Icon(Icons.perm_identity),
                          labelText: "请输入用户名",
                          helperText: "注册时填写的名字"),
                    ),
                    RaisedButton(
                        color: Colors.blueAccent,
                        child: Text("存储"),
                        onPressed: () {
                          save();
                          Scaffold.of(context).showSnackBar(
                              new SnackBar(content:  Text("数据存储成功")));
                        }),
                    RaisedButton(
                        color: Colors.greenAccent,
                        child: Text("获取"),
                        onPressed: () {
                          Future<String> userName = get();
                          userName.then((String userName) {
                            Scaffold.of(context).showSnackBar(
                                 SnackBar(content: Text("数据获取成功:$userName")));
                          });
                        }),
                  ],
                );
          }),
        ),
      );
    });
  }
}

Key-value file storage path



Author: hire inspectors to conquer the world
link: https: //www.jianshu.com/p/735b5684e900
Source: Jane books
are copyrighted by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/sd19871122/article/details/108226401