- Implement AppConfigService using path_provider to store settings in a local JSON file,\n ensuring configuration survives app updates/reinstalls.\n - Replace shared_preferences with AppConfigService in HomePage, SettingsPage,\n and RegistrationPage.\n - Replace shared_preferences with AppConfigService in HomePage, SettingsPage,\n and RegistrationPage.\n - Add HomePage.dart as the main navigation hub with feature cards (Registration,\n Boxing, Shelf Query) and dynamic connection status bar.\n - Remove Settings entry from RegistrationPage; Settings are only accessible from\n the Home page. Use 'flutter analyze' to verify the code.
54 lines
1.6 KiB
Dart
54 lines
1.6 KiB
Dart
import 'dart:io';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'dart:convert';
|
|
|
|
/// 应用全局配置服务 (替代 SharedPreferences)
|
|
/// 配置数据持久化为本地 JSON 文件,覆盖安装应用时数据不丢失。
|
|
class AppConfigService {
|
|
static const String _kConfigFileName = 'app_config.json';
|
|
static final Map<String, dynamic> _defaults = {'api_url': ''};
|
|
|
|
Future<String> get _filePath async {
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
return '${directory.path}/$_kConfigFileName';
|
|
}
|
|
|
|
/// 读取完整配置字典
|
|
Future<Map<String, dynamic>> loadConfig() async {
|
|
try {
|
|
final file = File(await _filePath);
|
|
if (await file.exists()) {
|
|
final jsonString = await file.readAsString();
|
|
return jsonDecode(jsonString) as Map<String, dynamic>;
|
|
}
|
|
} catch (e) {
|
|
debugPrint('[AppConfig] 读取配置失败: $e');
|
|
}
|
|
return Map<String, dynamic>.from(_defaults);
|
|
}
|
|
|
|
/// 读取字符串配置项
|
|
Future<String?> getString(String key) async {
|
|
final config = await loadConfig();
|
|
return config[key] as String?;
|
|
}
|
|
|
|
/// 保存字符串配置项
|
|
Future<void> setString(String key, String value) async {
|
|
final config = await loadConfig();
|
|
config[key.toString()] = value.toString();
|
|
await _saveConfig(config);
|
|
}
|
|
|
|
/// 完整写入 JSON 文件
|
|
Future<void> _saveConfig(Map<String, dynamic> config) async {
|
|
try {
|
|
final file = File(await _filePath);
|
|
await file.writeAsString(jsonEncode(config));
|
|
} catch (e) {
|
|
debugPrint('[AppConfig] 保存配置失败: $e');
|
|
}
|
|
}
|
|
}
|