You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.1 KiB
Dart

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../global.dart';
part 'site_config.g.dart';
@JsonSerializable()
class SiteConfig {
List<String> moduleStyles;
List<String> moduleScripts;
String renderTheme;
SiteConfig({
this.moduleStyles = const [],
this.moduleScripts = const [],
this.renderTheme = Global.renderThemeFallback,
});
factory SiteConfig.fromJson(Map<String, dynamic> json) => _$SiteConfigFromJson(json);
Map<String, dynamic> toJson() => _$SiteConfigToJson(this);
}
class AppSettingsController extends GetxController {
bool _ignoreSave = false;
bool isInit = false;
List<String> moduleStyles = [];
List<String> moduleScripts = [];
String renderTheme = Global.renderThemeFallback;
@override
void onInit() {
super.onInit();
loadFromStorage();
if (isInit) {
// 尝试更新APP配置
loadFromRemote();
}
}
/// 从本地存储读取
Future<void> loadFromStorage() async {
try {
final prefs = await SharedPreferences.getInstance();
var siteConfigJson = prefs.getString("siteConfigCache");
if (siteConfigJson == null) return;
var siteConfigObject = jsonDecode(siteConfigJson);
if (siteConfigObject == null) return;
var siteConfigData = SiteConfig.fromJson(siteConfigObject);
moduleScripts = siteConfigData.moduleScripts;
moduleStyles = siteConfigData.moduleStyles;
renderTheme = siteConfigData.renderTheme;
} catch (ex) {
if (kDebugMode) {
print(ex);
}
} finally {
_ignoreSave = false;
}
}
Future<void> loadFromRemote() async {}
/// 缓存到本地存储
void saveToStorage() {
if (_ignoreSave) return;
final prefs = Global.sharedPreferences!;
var siteConfigData = SiteConfig(
moduleScripts: moduleScripts,
moduleStyles: moduleStyles,
renderTheme: renderTheme,
);
var siteConfigJson = jsonEncode(siteConfigData.toJson());
prefs.setString("siteConfigCache", siteConfigJson);
}
}