shared_preferences:flutter数据存储

  1. 1. 概述
  2. 2. 设计概要
    1. 2.1 类设计
  3. 3. 代码模板
    1. 3.1 SpKeys
    2. 3.2 SpUtils
    3. 3.3 my_shared_preferences.dart

1. 概述

shared_preferences是flutter的简单的本地存储类。
example代码位置: example

2. 设计概要

shared_preferences在手机中的存储位置/data/data/com.kaisawind.flutter_example/shared_prefs/FlutterSharedPreferences.xml

shared_preferences使用xml进行本地存储,所以不能存储复杂的结构。

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="flutter.datetime">2019-09-21 13:34:54.468565</string>
</map>

2.1 类设计

创建SpKeys类管理存储的键,防止键重复。
创建SpUtils类管理存储,可以追加判断,日志等。

3. 代码模板

3.1 SpKeys

class SpKeys {
  static const datetime = 'datetime';
}

3.2 SpUtils

import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';

/// 用来做shared_preferences的存储
class SpUtil {
  static SpUtil _instance;
  static Future<SpUtil> get instance async {
    return await getInstance();
  }

  static SharedPreferences _spf;

  SpUtil._();

  Future _init() async {
    _spf = await SharedPreferences.getInstance();
  }

  static Future<SpUtil> getInstance() async {
    if (_instance == null) {
      _instance = new SpUtil._();
      await _instance._init();
    }
    return _instance;
  }

  static bool _beforeCheck() {
    if (_spf == null) {
      return true;
    }
    return false;
  }

  // 判断是否存在数据
  bool hasKey(String key) {
    Set keys = getKeys();
    return keys.contains(key);
  }

  Set<String> getKeys() {
    if (_beforeCheck()) return null;
    return _spf.getKeys();
  }

  get(String key) {
    if (_beforeCheck()) return null;
    return _spf.get(key);
  }

  getString(String key) {
    if (_beforeCheck()) return null;
    return _spf.getString(key);
  }

  Future<bool> setString(String key, String value) {
    if (_beforeCheck()) return null;
    return _spf.setString(key, value);
  }

  bool getBool(String key) {
    if (_beforeCheck()) return null;
    return _spf.getBool(key);
  }

  Future<bool> setBool(String key, bool value) {
    if (_beforeCheck()) return null;
    return _spf.setBool(key, value);
  }

  int getInt(String key) {
    if (_beforeCheck()) return null;
    return _spf.getInt(key);
  }

  Future<bool> setInt(String key, int value) {
    if (_beforeCheck()) return null;
    return _spf.setInt(key, value);
  }

  double getDouble(String key) {
    if (_beforeCheck()) return null;
    return _spf.getDouble(key);
  }

  Future<bool> setDouble(String key, double value) {
    if (_beforeCheck()) return null;
    return _spf.setDouble(key, value);
  }

  List<String> getStringList(String key) {
    return _spf.getStringList(key);
  }

  Future<bool> setStringList(String key, List<String> value) {
    if (_beforeCheck()) return null;
    return _spf.setStringList(key, value);
  }

  dynamic getDynamic(String key) {
    if (_beforeCheck()) return null;
    return _spf.get(key);
  }

  Future<bool> remove(String key) {
    if (_beforeCheck()) return null;
    return _spf.remove(key);
  }

  Future<bool> clear() {
    if (_beforeCheck()) return null;
    return _spf.clear();
  }
}

3.3 my_shared_preferences.dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_example/resources/sp_keys.dart';

class MySharedPreferences extends StatefulWidget {
  @override
  _MySharedPreferencesState createState() => _MySharedPreferencesState();
}

class _MySharedPreferencesState extends State<MySharedPreferences> {
  String _date = '';

  _MySharedPreferencesState() : super();

  @override
  void initState() {
    super.initState();
    setDate();
  }

  void setDate() async {
    DateTime now = DateTime.now();
    SharedPreferences sp = await SharedPreferences.getInstance();
    await sp.setString(SpKeys.datetime, now.toString());
  }

  void updateDate() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    setState(() {
      _date = sp.getString(SpKeys.datetime);
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text('Shared Preferences'),
      ),
      body: ListView(
        children: <Widget>[
          RaisedButton(
            child: Text('setString'),
            onPressed: () {
              setDate();
            },
          ),
          RaisedButton(
            child: Text('getString'),
            onPressed: () {
              updateDate();
            },
          ),
          Container(
            child: Align(
              child: Text(_date),
            ),
          ),
        ],
      ),
    );
  }
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 wind.kaisa@gmail.com

文章标题:shared_preferences:flutter数据存储

本文作者:kaisawind

发布时间:2019-09-21, 12:49:46

最后更新:2020-08-10, 08:17:32

原始链接:https://kaisawind.gitee.io/2019/09/21/2019-09-21-flutter-Sp/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏