config.dart 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import 'dart:convert';
  2. import 'package:flyinsono/architecture/config/model.dart';
  3. import 'package:flyinsono/architecture/storage/text_storage.dart';
  4. import 'package:get/get.dart';
  5. import 'package:fis_common/logger/logger.dart';
  6. /// 配置服务
  7. class ConfigService extends GetxService {
  8. ConfigService._() {
  9. _persistenceStorage = TextStorage.createInstance(_PERSISTENCE_FILENAME);
  10. }
  11. /// 全局单例
  12. static ConfigService get ins => Get.find();
  13. ///持久化配置文件名
  14. static const _PERSISTENCE_FILENAME = "config.conf";
  15. late TextStorage _persistenceStorage;
  16. late ConfigModel _cache;
  17. /// 配置数据
  18. ConfigModel get data => _cache;
  19. /// 实例初始化
  20. static Future<ConfigService> init() async {
  21. if (Get.isRegistered<ConfigService>()) return ins;
  22. final instance = ConfigService._();
  23. await instance._loadPersistenceData();
  24. return instance;
  25. }
  26. ///重新加载
  27. static Future<ConfigService> reload() async {
  28. if (Get.isRegistered<ConfigService>()) {
  29. Get.delete<ConfigService>(force: true);
  30. }
  31. final instance = ConfigService._();
  32. await instance._loadPersistenceData();
  33. return instance;
  34. }
  35. /// 保存配置
  36. Future<bool> save() async {
  37. try {
  38. final jsonMap = _cache.toJson();
  39. final jsonText = jsonEncode(jsonMap);
  40. final saved = await _persistenceStorage.save(jsonText);
  41. return saved;
  42. } catch (e) {
  43. logger.e("ConfigService save data error.", e);
  44. return false;
  45. }
  46. }
  47. Future<void> _loadPersistenceData() async {
  48. try {
  49. var text = await _persistenceStorage.fetch();
  50. _setDataFromJson(text);
  51. } catch (e) {
  52. logger.e("ConfigService load persistence data error.", e);
  53. }
  54. }
  55. void _setDataFromJson(String? jsonText) {
  56. final isObjJson = jsonText != null &&
  57. jsonText.length > 1 &&
  58. jsonText.startsWith("{") &&
  59. jsonText.endsWith("}");
  60. var jsonMap = jsonDecode(isObjJson ? jsonText : "{}");
  61. _cache = ConfigModel.fromJson(jsonMap);
  62. }
  63. }