Blame view

lib/common/core/module_cache.dart 2.07 KB
42f15f6c   吴启风   feat:模块选择持久化&模块主题...
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  import 'dart:convert';
  import 'dart:ui';
  
  import '../../models/course_module_entity.dart';
  import '../../utils/sp_util.dart';
  import '../utils/color_parser.dart';
  
  ///模块缓存类
  class ModuleCache {
    // Private constructor
    ModuleCache._privateConstructor();
  
    // Singleton instance
    static final ModuleCache _instance = ModuleCache._privateConstructor();
  
    // Public accessor for the singleton instance
    static ModuleCache get instance => _instance;
  
    // Variable to store the current module entity
    CourseModuleEntity? _currentModule;
  
    // Key for SharedPreferences
    static const String _moduleKey = "courseModule";
  
    // Initialize the cache by loading data from SharedPreferences
    Future<void> init() async {
      String? jsonString = SpUtil.getInstance().get<String>(_moduleKey);
      if (jsonString != null) {
        _currentModule = CourseModuleEntity.fromJson(json.decode(jsonString));
      }
    }
  
    // Getter and setter for the current module
    CourseModuleEntity? get currentModule => _currentModule;
    set currentModule(CourseModuleEntity? value) {
      _currentModule = value;
      _saveToPrefs(value);
    }
  
    // Method to clear the cached module data
    void clear() {
      _currentModule = null;
      _clearPrefs();
    }
  
    // Save module data to SharedPreferences
    void _saveToPrefs(CourseModuleEntity? module) {
      if (module != null) {
        String jsonString = json.encode(module.toJson());
        SpUtil.getInstance().setData(_moduleKey, jsonString);
      } else {
        SpUtil.getInstance().remove(_moduleKey);
      }
    }
  
    String getCurrentThemeColorStr({String? colorStr}) {
      return colorStr ?? _currentModule.getSafeThemeColor();
    }
  
    ///根据当前课程阶段获取系统主题色
    Color getCurrentThemeColor({String? colorStr}) {
      return parseColor(getCurrentThemeColorStr(colorStr: colorStr));
    }
  
    ///根据当前课程阶段获取系统主题名称
    String getCurrentThemeName({String? name}) {
      return name ?? _currentModule.getSafeName();
    }
  
    // Clear all data from SharedPreferences
    void _clearPrefs() async {
      SpUtil.getInstance().remove(_moduleKey);
    }
  }