Blame view

lib/utils/sp_util.dart 1.21 KB
94342c3f   Key   feat: user util
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  import 'package:shared_preferences/shared_preferences.dart';
  
  class SpUtil {
    SharedPreferences? _prefs;
    static SpUtil? _instance;
  
    SpUtil.of() {
      init();
    }
    SpUtil._pre(SharedPreferences prefs) {
      _prefs = prefs;
    }
  
    static SpUtil getInstance() {
      _instance ??= SpUtil.of();
      return _instance!;
    }
  
    void init() async {
      _prefs ??= await SharedPreferences.getInstance();
    }
  
    static Future<SpUtil> preInit() async {
      if (_instance == null) {
        var prefs = await SharedPreferences.getInstance();
        _instance = SpUtil._pre(prefs);
      }
      return _instance!;
    }
  
6c23b545   吴启风   fix: 修复友盟隐私合规初始化时机
31
    Future<void> setData<T>(String key, T data) async {
94342c3f   Key   feat: user util
32
      if (data is String) {
6c23b545   吴启风   fix: 修复友盟隐私合规初始化时机
33
        await _prefs?.setString(key, data);
94342c3f   Key   feat: user util
34
      } else if (data is double) {
6c23b545   吴启风   fix: 修复友盟隐私合规初始化时机
35
        await _prefs?.setDouble(key, data);
94342c3f   Key   feat: user util
36
      } else if (data is int) {
6c23b545   吴启风   fix: 修复友盟隐私合规初始化时机
37
        await _prefs?.setInt(key, data);
94342c3f   Key   feat: user util
38
      } else if (data is bool) {
6c23b545   吴启风   fix: 修复友盟隐私合规初始化时机
39
        await _prefs?.setBool(key, data);
94342c3f   Key   feat: user util
40
      } else if (data is List<String>) {
6c23b545   吴启风   fix: 修复友盟隐私合规初始化时机
41
        await _prefs?.setStringList(key, data);
94342c3f   Key   feat: user util
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
      }
    }
  
    void remove(String key) {
      _prefs?.remove(key);
    }
  
    T? get<T>(String key) {
      var value = _prefs?.get(key);
      if (value != null) {
        return value as T;
      }
      return null;
    }
  }