12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import 'dart:convert';
- import 'package:shared_preferences/shared_preferences.dart';
- class SpUtil {
- static Future<SharedPreferences> sharedPreferences =
- SharedPreferences.getInstance();
- static Future<T> get<T>(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<String>) {
- return s.getStringList(key) as T;
- }
- if (defaultValue is List<Map>) {
- List<String>? 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<bool> save<T>(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<String>) {
- return s.setStringList(key, value);
- }
- if (value is List<Map>) {
- List<String> 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<bool> remove(String key) {
- return sharedPreferences.then((s) {
- return s.remove(key);
- });
- }
- static Future<bool> clear() {
- return sharedPreferences.then((s) {
- return s.clear();
- });
- }
- }
|