import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; class SpUtil { static Future sharedPreferences = SharedPreferences.getInstance(); static Future get(String key, T defaultValue) { return sharedPreferences.then((s) { if (s.get(key) == null) { return defaultValue; } else { if (defaultValue is int) { return s.getInt(key) as T; } if (defaultValue is double) { return s.getDouble(key) as T; } if (defaultValue is String) { return s.getString(key) as T; } if (defaultValue is List) { return s.getStringList(key) as T; } if (defaultValue is List) { List? dataList = s.getStringList(key); return dataList?.map((value) { return json.decode(value); }).toList() as T; } if (defaultValue is bool) { return s.getBool(key) as T; } return s.get(key) as T; } }); } static Future save(String key, T value) async { return sharedPreferences.then((s) { if (value == null) { return s.remove(key); } else { if (value is int) { return s.setInt(key, value); } if (value is double) { return s.setDouble(key, value); } if (value is String) { return s.setString(key, value); } if (value is List) { return s.setStringList(key, value); } if (value is List) { List dataList = value.map((value) { return json.encode(value); }).toList(); return s.setStringList(key, dataList); } if (value is bool) { return s.setBool(key, value); } } return false; }); } static Future remove(String key) { return sharedPreferences.then((s) { return s.remove(key); }); } static Future clear() { return sharedPreferences.then((s) { return s.clear(); }); } }