flutter中使用shared_preferences的存储
添加依赖
shared_preferences: ^0.5.1+2
工具类
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> putString(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> putBool(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> putInt(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> putDouble(String key, double value) { if (_beforeCheck()) return null; return _spf.setDouble(key, value); } List<String> getStringList(String key) { return _spf.getStringList(key); } Future<bool> putStringList(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(); } }
使用:
SpUtil sp = await SpUtil.getInstance(); int value =sp.getInt(”key“);
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!
posted on 2019-09-19 20:35 LoaderMan 阅读(2015) 评论(0) 编辑 收藏 举报