注意:使用 flutter 的时候一定要把数据放在父组件中(主要是指Dio数据请求),往子组件传展示
待做
1、dependencies:
shared_preferences: ^2.2.2
2、utils 包里面创建文件:
shared_preferences.dart
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class JSpUtil {
JSpUtil._internal();
factory JSpUtil() => _instance;
static final JSpUtil _instance = JSpUtil._internal();
static late SharedPreferences _preferences;
static Future<JSpUtil> getInstance() async {
_preferences = await SharedPreferences.getInstance();
return _instance;
}
/// 通用设置持久化数据
static setLocalStorage<T>(String key, T value) {
String type = value.runtimeType.toString();
switch (type) {
case "String":
_preferences.setString(key, value as String);
break;
case "int":
_preferences.setInt(key, value as int);
break;
case "bool":
_preferences.setBool(key, value as bool);
break;
case "double":
_preferences.setDouble(key, value as double);
break;
case "List<String>":
_preferences.setStringList(key, value as List<String>);
break;
}
}
/// 获取持久化数据
static dynamic getLocalStorage<T>(String key) {
dynamic value = _preferences.get(key);
if (value.runtimeType.toString() == "String") {
if (_isJson(value)) {
return json.decode(value);
}
}
return value;
}
/// 获取持久化数据中所有存入的key
static Set<String> getKeys() {
return _preferences.getKeys();
}
/// 获取持久化数据中是否包含某个key
static bool containsKey(String key) {
return _preferences.containsKey(key);
}
/// 删除持久化数据中某个key
static Future<bool> remove(String key) async {
return await _preferences.remove(key);
}
/// 清除所有持久化数据
static Future<bool> clear() async {
return await _preferences.clear();
}
/// 重新加载所有数据,仅重载运行时
static Future<void> reload() async {
return await _preferences.reload();
}
/// 判断是否是json字符串
static _isJson(String value) {
try {
const JsonDecoder().convert(value);
return true;
} catch(e) {
return false;
}
}
}
3、入口函数加上两句话,不然报错
void main() async {
// 下面两句是持久化数据用的
WidgetsFlutterBinding.ensureInitialized();
await JSpUtil.getInstance();
runApp(const ApplicationApp());
}
4、使用
// 1、取值
JSpUtil.getLocalStorage('token');
// 2、存值
JSpUtil.setLocalStorage("token", "需要存的值");
1、创建 store 仓库
// 根目录下创建 store/store.dart 文件
// store.dart 文件里面
import 'package:get/get.dart';
import 'package:hook_up_rant/utils/shared_preferences.dart';
class StoreIndex {
// 变量(首先从本地储存取,没有的话就定义一个)
static var token =