Flutter 本地固化之 SharedPreferences 封装

直接上代码了
(如果有写的不完善的地方,欢迎指正)

新的改动

#重新调整了下, 这里吧几个基础方法变为内部静态函数, 不对外提供
#提供以key 为函数名的静态方法,指定枚举类型来供外部使用

  /// *********************************** SharePreferencesUtils 静态私有方法 ***********************************
  ///
  ///
  /// 存/更 - 进行json序列化, 均为json字符串形式保存
  /// 成功返回 Future 的成功态
  /// 失败 抛出异常信息
  static Future<dynamic> _saveToLocalMap(String key, dynamic value) async {
    final com = Completer();
    final future = com.future;
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String jsonEncodestr = jsonEncode(value);
      prefs.setString(key, jsonEncodestr);
      com.complete(true);
      print('======= json序列化的待存储字符串 ======== :  ' + jsonEncodestr);
      print(' save  is  ok ,,,,,');
    } catch (err) {
      com.complete(false);
      print(' save  is  err ,,,,,');
      print(err.toString());
    }
    return future;
  }

  /// 删 - 根据key 删除对应的数据
  /// 成功返回 Future 的成功态
  /// 失败 抛出异常信息
  static Future<dynamic> _deleteFromLocalMap(String key) async {
    final com = Completer();
    final future = com.future;
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.remove(key);
      com.complete(true);
      print(' delete  is  ok ,,,,,');
    } catch (err) {
      com.complete(false);
      print(' delete  is  err ,,,,,');
      print(err.toString());
    }
    return future;
  }

  /// 取 - 读取key 对应的json序列化字符串,并进行反序列化
  /// 成功返回 Future 的成功对象
  /// 失败 抛出异常信息
  static Future<dynamic> _readFromLocalMap(String key) async {
    final com = Completer();
    final future = com.future;
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      final values = prefs.get(key);
      var obj = jsonDecode(values);
      com.complete(obj);
      print('======= json反序列化后的dynamic对象 ======== :  ' + obj.toString());
      print(' read  is  ok ,,,,,');
    } catch (err) {
      // 读取失败, 仅返回一个null, 防止外部不catch,引起报错, 但是外部就需要做好判空
      com.complete(null);
      print(' read  is  err ,,,,,');
    }
    return future;
  }

  /// *********************************** SharePreferencesUtils 静态方法 ***********************************
  /// 存取删tokey
  /// [SharePreferencesUtilsWorkType] 指定操作模式
  static token(SharePreferencesUtilsWorkType type, {dynamic value}) {
    String key = 'token';
    if (type == SharePreferencesUtilsWorkType.save) {
      return _saveToLocalMap(key, value);
    }
    if (type == SharePreferencesUtilsWorkType.remove) {
      return _deleteFromLocalMap(key);
    }
    if (type == SharePreferencesUtilsWorkType.get) {
      return _readFromLocalMap(key);
    }
  }

使用

    // 请求前, 获取一下token塞进报文headers
    var token = await SharePreferencesUtils.token(SharePreferencesUtilsWorkType.get);


      bool saveScuess = await SharePreferencesUtils.token(SharePreferencesUtilsWorkType.save, value: token);
      saveScuess ? debugPrint('token 保存成功') : debugPrint('token 保存失败');

========= 旧的内容 =======

import 'dart:async';

/// -------------------------------
/// Created with Flutter Dart File.
/// User [email protected]
/// Date: 2020-08-17
/// Time: 13:44
/// Des: 类似于 iOS的NSUserDefaults和Android的SharedPreferences 轻量级存储类
/// -------------------------------

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

class SharePreferencesUtils {
  /// 存/更 - 进行json序列化, 均为json字符串形式保存
  /// 成功返回 Future 的成功态
  /// 失败 抛出异常信息
  static Future<dynamic> saveToLocalMap(String key, dynamic value) async {
    final com = Completer();
    final future = com.future;
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String jsonEncodestr = jsonEncode(value);
      prefs.setString(key, jsonEncodestr);
      com.complete(true);
      print('======= json序列化的待存储字符串 ======== :  ' + jsonEncodestr);
      print(' save  is  ok ,,,,,');
    } catch (err) {
      com.complete(false);
      print(' save  is  err ,,,,,');
      print(err.toString());
    }
    return future;
  }

  /// 删 - 根据key 删除对应的数据
  /// 成功返回 Future 的成功态
  /// 失败 抛出异常信息
  static Future<dynamic> deleteFromLocalMap(String key) async {
    final com = Completer();
    final future = com.future;
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.remove(key);
      com.complete(true);
      print(' delete  is  ok ,,,,,');
    } catch (err) {
      com.complete(false);
      print(' delete  is  err ,,,,,');
      print(err.toString());
    }
    return future;
  }

  /// 取 - 读取key 对应的json序列化字符串,并进行反序列化
  /// 成功返回 Future 的成功对象
  /// 失败 抛出异常信息
  static Future<dynamic> readFromLocalMap(String key) async {
    final com = Completer();
    final future = com.future;
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      final values = prefs.get(key);
      var obj = jsonDecode(values);
      com.complete(obj);
      print('======= json反序列化后的dynamic对象 ======== :  ' + obj.toString());
      print(' read  is  ok ,,,,,');
    } catch (err) {
      // 读取失败, 仅返回一个null, 防止外部不catch,引起报错, 但是外部就需要做好判空
      com.complete(null);
      print(' read  is  err ,,,,,');
    }
    return future;
  }
}

使用


  /// *********************************** fun ***********************************
  _onTap(BuildContext ctx, int index) async {
    switch (index) {
      case 1:
        {
          var saveScuess = await SharePreferencesUtils.saveToLocalMap('name', {
            '111': [1, 33, 3, "ddf"]
          });
          print(saveScuess);
        }
        break;
      case 2:
        {
          var removeSuc = await SharePreferencesUtils.readFromLocalMap('name');
          print(removeSuc);
        }
        break;
      case 3:
        {
          var res = await SharePreferencesUtils.deleteFromLocalMap('name');
          print(res.toString());
        }
        break;
    }
  }

log

I/flutter (19053): ======= json序列化的待存储字符串 ======== :  {"111":[1,33,3,"ddf"]}
I/flutter (19053):  save  is  ok ,,,,,
I/flutter (19053): true
I/flutter (19053): ======= json反序列化后的dynamic对象 ======== :  {111: [1, 33, 3, ddf]}
I/flutter (19053):  read  is  ok ,,,,,
I/flutter (19053): {111: [1, 33, 3, ddf]}
I/flutter (19053):  delete  is  ok ,,,,,
I/flutter (19053): true

你可能感兴趣的:(Flutter,Flutter本地固化,本地存储,SharedPreferenc,Future,Compeleter)