更新UI,修复无法搜索模组问题,增加了爱发电窗口

This commit is contained in:
ZV authored and venti1112 committed 2026-11-18 21:31:08 +08:00
1 parent e32125aa8e
commit 06445710da
24 files changed
+1093 -106

No files matched your search

+16 -2
View File
@@ -9,10 +9,14 @@ import 'core/utils/update_service.dart';
import 'core/widgets/background_widget.dart';
import 'providers/wallpaper_provider.dart';
import 'core/widgets/user_agreement_dialog.dart'; // 新增
import 'core/widgets/z_widgets.dart';
import 'features/shell/main_shell.dart';
import 'providers/theme_provider.dart';
import 'providers/language_provider.dart';
import 'providers/download_provider.dart';
import 'providers/server_provider.dart';
import 'providers/rcon_provider.dart';
import 'core/services/server_monitor_service.dart';
import 'features/dashboard/server_picker_bar.dart';
/// 全局导航 Key
@@ -98,6 +102,14 @@ class ZVManagerAppState extends State<ZVManagerApp> {
// 这里绝不能再 create 新实例 —— 否则会生成一个空的影子 Provider,
// 导致更新后服务器列表"被清空"、添加时覆盖真实数据(v2.0 实测 bug)。
ChangeNotifierProvider(create: (_) => DownloadProvider()),
// 状态监控:复用 Bootstrap 里已预加载的 ServerProvider / RconProvider,
// 在 create 里惰性启动,避免拖慢冷启动。
ChangeNotifierProvider<ServerMonitorService>(
create: (ctx) => ServerMonitorService(
servers: ctx.read<ServerProvider>(),
rcon: ctx.read<RconProvider>(),
)..load(),
),
ChangeNotifierProvider(create: (_) => LanguageProvider()),
ChangeNotifierProvider(create: (_) => SelectedServerHolder()),
// 复用 main() 中预加载的实例,不能在这里 create 一个新的
@@ -107,12 +119,14 @@ class ZVManagerAppState extends State<ZVManagerApp> {
],
child: Consumer2<ThemeProvider, LanguageProvider>(
builder: (context, themeProvider, languageProvider, child) {
// 全站强调色跟随当前主题配色(z_widgets 内组件共用同一个变量)
kZAccent = themeProvider.themeColor.seed;
return MaterialApp(
title: 'ZV Manager',
debugShowCheckedModeBanner: false,
navigatorKey: navigatorKey,
theme: AppTheme.lightTheme,
darkTheme: AppTheme.darkTheme,
theme: AppTheme.lightThemeFor(themeProvider.themeColor),
darkTheme: AppTheme.darkThemeFor(themeProvider.themeColor),
themeMode: themeProvider.flutterThemeMode,
locale: languageProvider.locale,
localizationsDelegates: const [
+75 -1
View File
@@ -166,6 +166,9 @@ class S {
'选择图片': 'Pick image',
'选择视频': 'Pick video',
'清除背景': 'Clear background',
'界面显示语言': 'Display language',
'选择一张图片或一段视频作为应用背景':
'Pick an image or a video as the app background',
'使用教程(模组/终端等)': 'Tutorials (mods / terminal etc.)',
// ---- 模板插值 ----
'服务器「{0}」已断开连接!': 'Server "{0}" disconnected!',
@@ -253,6 +256,8 @@ class S {
'Q: Console connects but the mods page says no SSH? → Edit the server, enable SSH and fill in the credentials',
'Q:连接失败?→ 检查防火墙是否放行端口、地址端口是否填对、服务器是否在线':
'Q: Connection failed? → Check firewall rules for the port, verify address/port, and confirm the server is online',
'Q:开了监控却收不到通知?→ 检查系统是否允许本应用通知、是否开了省电限制':
'Q: Monitoring is on but no alerts? → Check that notifications are allowed for this app and battery saving is not restricting it',
'SSH 拥有服务器完全控制权,请勿随意执行不熟悉的命令':
'SSH grants full server control; do not run unfamiliar commands carelessly',
'SSH 是服务器自带的远程管理服务,绝大多数独立服务器默认已开启(端口 22)':
@@ -268,7 +273,20 @@ class S {
'一、如何开启 RCON(必配,控制台/玩家管理需要)':
'1. How to enable RCON (required for console/player management)',
'一、软件性质与用途': '1. Nature and Purpose of the Software',
'七、常见问题': '7. FAQ',
'七、状态监控与通知': '7. Status Monitoring and Notifications',
'进入「我的」→ 设置 → 「状态监控」,打开总开关':
'Open Me → Settings → "Status monitoring" and turn the switch on',
'首次开启会申请通知权限(Android 13+),请点「允许」,否则提醒会被系统丢弃':
'The first time you enable it, Android 13+ asks for notification permission — tap Allow, otherwise alerts are dropped',
'按需开启「服务器离线 / 服务器恢复 / 玩家上线」三类提醒':
'Enable the offline / recovered / player-join alerts you want',
'「检查间隔」可选 30 秒 / 1 / 2 / 5 分钟,间隔越短发现越快、轮询压力越大':
'"Check interval" can be 30 s / 1 / 2 / 5 min; shorter is faster but polls more',
'点「立即检查一次」可手动验证 RCON 配置是否可用':
'Tap "Check now" to verify the RCON configuration manually',
'提醒依赖 App 进程存活:彻底关闭 App 或被系统省电策略限制时不会推送':
'Alerts need the app process alive: nothing is pushed once the app is fully closed or restricted by battery saving',
'八、常见问题': '8. FAQ',
'七、数据与隐私': '7. Data and Privacy',
'三、合法使用(重要)': '3. Lawful Use (Important)',
'三、模组 / 插件管理怎么用': '3. Using Mod / Plugin Management',
@@ -522,6 +540,62 @@ class S {
'请选择一台已配置 SSH 的服务器': 'Select a server with SSH configured',
'从 Gitee 获取最新版本': 'Fetch the latest version from Gitee',
'查看本应用使用的第三方库许可': 'View third-party licenses used by this app',
'支持作者 · 爱发电': 'Support us on Afdian',
'通过爱发电支持项目开发': 'Support development via Afdian',
'赞助链接待配置': 'Sponsor link not configured yet',
'加入官方 QQ 群': 'Join our QQ group',
'与开发者和其他用户交流': 'Chat with the developer and other users',
'群号已复制,打开 QQ 搜索加群':
'Group number copied — open QQ and search to join',
// ---- 多主题 / 胶囊开关 ----
'深色模式': 'Dark mode',
'跟随系统': 'Follow system',
'主题配色': 'Theme color',
'开启后使用暗色界面': 'Use the dark interface',
'跟随系统开启时由系统决定,关闭后可手动切换':
'Follows the system; turn off Follow system to set it manually',
'随系统的深色 / 浅色设置自动切换': 'Switch automatically with the system theme',
'切换全站强调色与界面色调': 'Change the accent color across the app',
'ZL2 绿': 'ZL2 Green',
'海蓝': 'Ocean Blue',
'星紫': 'Violet',
'暖橙': 'Sunset Orange',
'樱粉': 'Sakura Pink',
// ---- 状态监控与通知 ----
'状态监控': 'Status monitoring',
'开启后定时检查服务器状态,并在变化时推送通知':
'Periodically checks server status and pushes alerts on changes',
'每 {0}检查一次 · 最近 {1}': 'Every {0} · last check {1}',
'服务器离线提醒': 'Offline alerts',
'服务器掉线时推送系统通知':
'Send a system notification when a server goes offline',
'服务器恢复提醒': 'Recovery alerts',
'服务器重新上线时推送通知':
'Send a notification when a server comes back online',
'玩家上线提醒': 'Player join alerts',
'有新玩家进入服务器时推送通知':
'Send a notification when a player joins a server',
'检查间隔': 'Check interval',
'间隔越短发现越快,对服务器的轮询压力也越大':
'Shorter intervals detect changes faster but poll the server more',
'立即检查一次': 'Check now',
'正在检查…': 'Checking…',
'手动跑一轮检查,用来确认 RCON 配置是否可用':
'Run one check manually to verify the RCON configuration',
'30 秒': '30 s',
'1 分钟': '1 min',
'2 分钟': '2 min',
'5 分钟': '5 min',
'尚未检查': 'not yet',
'检查完成:{0} 台服务器在线': 'Check complete: {0} server(s) online',
'未获得通知权限,提醒可能无法显示,请到系统设置中允许通知':
'Notification permission was not granted; alerts may not appear',
'服务器离线': 'Server offline',
'服务器恢复': 'Server recovered',
'玩家上线': 'Player joined',
'「{0}」已离线,可能已停止运行': '"{0}" is offline and may have stopped',
'「{0}」已恢复在线': '"{0}" is back online',
'「{0}」:{1} 进入服务器': '"{0}": {1} joined the server',
};
static String t(String zh) => en ? (_en[zh] ?? zh) : zh;
+112
View File
@@ -0,0 +1,112 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
/// 系统通知服务:把服务器状态事件推送到 Android 通知栏。
///
/// 设计要点:
/// - **绝不阻断主流程**:所有插件调用都包了 try/catch。Web 端、用户拒绝权限、
/// 厂商 ROM 屏蔽通知时静默降级,只记一条 debugPrint,不让监控逻辑崩掉;
/// - **单例**:监控服务与设置页共用同一个实例,避免重复注册通知通道;
/// - **懒初始化**:只有真正要用时才初始化,不给冷启动增加负担
/// (App 启动已经有一段 6 秒的加载兜底,不该再塞一个插件初始化进去)。
class NotificationService {
NotificationService._();
static final NotificationService instance = NotificationService._();
/// 通知通道 id:Android 8+ 的通道一旦创建,重要性就只能由用户改,
/// 所以这里的 id 要保持永久稳定,换名字会让旧通道失效。
static const String _channelId = 'zv_server_monitor';
static const String _channelName = '服务器状态监控';
static const String _channelDesc = '服务器离线、恢复与玩家上线提醒';
final FlutterLocalNotificationsPlugin _plugin =
FlutterLocalNotificationsPlugin();
bool _initialized = false;
bool _permission = false;
/// 初始化成功且拿到通知权限,才认为可以真正弹通知。
bool get isReady => _initialized && _permission;
/// 初始化插件与通知通道。重复调用安全。
Future<void> init() async {
if (kIsWeb || _initialized) return;
try {
// 图标必须指向 res/drawable 下的纯白剪影,见 ic_stat_monitor.xml
const settings = InitializationSettings(
android: AndroidInitializationSettings('ic_stat_monitor'),
);
await _plugin.initialize(settings);
_initialized = true;
} catch (e) {
debugPrint('通知服务初始化失败: $e');
}
}
/// 请求通知权限(Android 13+ 必须运行时授权;更低版本直接视为已授权)。
///
/// 返回最终是否可用。授权被拒时不影响监控继续跑,只是不弹通知。
Future<bool> ensurePermission() async {
if (kIsWeb) return false;
await init();
if (!_initialized) return false;
if (_permission) return true;
try {
final android = _plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
final granted = await android?.requestNotificationsPermission();
// 低版本系统该方法可能返回 null,此时按「已授权」处理
_permission = granted ?? true;
} catch (e) {
debugPrint('请求通知权限失败: $e');
_permission = false;
}
return _permission;
}
/// 静默检查「现在能不能发通知」:初始化插件 + 查询系统是否已允许,
/// **不会弹授权框**。用于 App 重启后恢复监控时判断,避免每次冷启动
/// 都拿系统权限弹窗打扰用户。
Future<bool> _ensureReady() async {
if (kIsWeb) return false;
await init();
if (!_initialized) return false;
if (_permission) return true;
try {
final android = _plugin.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
final enabled = await android?.areNotificationsEnabled();
_permission = enabled ?? true;
} catch (e) {
debugPrint('查询通知开关失败: $e');
_permission = false;
}
return _permission;
}
/// 弹一条通知。[id] 相同会覆盖上一条,调用方应使用递增 id。
Future<void> show({
required int id,
required String title,
required String body,
}) async {
if (!await _ensureReady()) return;
final details = NotificationDetails(
android: AndroidNotificationDetails(
_channelId,
_channelName,
channelDescription: _channelDesc,
importance: Importance.high,
priority: Priority.high,
// 长文本(多个玩家同时上线)展开后能看全,而不是被截断
styleInformation: BigTextStyleInformation(body),
),
);
try {
await _plugin.show(id, title, body, details);
} catch (e) {
debugPrint('发送通知失败: $e');
}
}
}
@@ -0,0 +1,309 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../providers/rcon_provider.dart';
import '../../providers/server_provider.dart';
import '../l10n/strings.dart';
import '../utils/rcon_client.dart';
import 'notification_service.dart';
/// 从 `list` 命令的返回里解析在线玩家名。
///
/// 只取最后一个冒号(兼容全角)之后的玩家段,再按逗号切分。
/// 零人在线时服务端返回的玩家段为空,直接得到空列表。
/// 解析不出的内容一律跳过,不抛异常 —— 监控是后台任务,不能因为
/// 某个服务端改了输出格式就把整轮检查搞崩。
List<String> parseOnlinePlayerNames(String? info) {
if (info == null) return const <String>[];
final cleaned = stripMinecraftCodes(info).trim();
final parts = cleaned.split(RegExp(r'[::]'));
if (parts.length < 2) return const <String>[];
final section = parts.last.trim();
if (section.isEmpty) return const <String>[];
return section
.split(RegExp(r'[,,]'))
.map((e) => e.trim())
.where((e) => e.isNotEmpty)
.toList();
}
/// 单台服务器的上一次观测快照。
class _ServerSnapshot {
bool online;
Set<String> players;
/// 最近一次弹通知的时间,用于抖动保护(避免网络抖动导致刷屏)。
DateTime? lastAlertAt;
_ServerSnapshot({
required this.online,
required this.players,
this.lastAlertAt,
});
}
/// 服务器状态监控:定时轮询所有已配置服务器,在状态变化时推送系统通知。
///
/// 监控规则(只对「状态变化」发通知,避免重复打扰):
/// - 在线 → 离线:服务器离线提醒;
/// - 离线 → 在线:服务器恢复提醒;
/// - 在线且出现新玩家:玩家上线提醒(一次轮询内多人同时上线会合并成一条);
/// - **首次观测只建立基线**,不发通知 —— 否则一开开关就会收到一串噪音。
///
/// 生命周期:由 App 层注册为 Provider,设置页开关控制启停。
class ServerMonitorService extends ChangeNotifier {
ServerMonitorService({required this.servers, required this.rcon});
final ServerProvider servers;
final RconProvider rcon;
// ---------- 持久化 key(一旦发布就不要改名,否则老用户设置会丢) ----------
static const String _kEnabled = 'monitor_enabled';
static const String _kOffline = 'monitor_notify_offline';
static const String _kRecovered = 'monitor_notify_recovered';
static const String _kJoin = 'monitor_notify_join';
static const String _kInterval = 'monitor_interval_sec';
/// 可选轮询间隔(秒)。太短的间隔会给服务器 RCON 带来无谓压力。
static const List<int> intervalOptions = <int>[30, 60, 120, 300];
bool _enabled = false;
bool _notifyOffline = true;
bool _notifyRecovered = true;
bool _notifyJoin = true;
int _intervalSec = 60;
Timer? _timer;
bool _checking = false;
bool _disposed = false;
DateTime? _lastCheckAt;
int _onlineCount = 0;
int _notifySeq = 0;
final Map<String, _ServerSnapshot> _snapshots = {};
bool get enabled => _enabled;
bool get notifyOffline => _notifyOffline;
bool get notifyRecovered => _notifyRecovered;
bool get notifyJoin => _notifyJoin;
int get intervalSec => _intervalSec;
bool get isChecking => _checking;
DateTime? get lastCheckAt => _lastCheckAt;
/// 最近一轮检查中被判定为在线的服务器数量。
int get onlineCount => _onlineCount;
/// 当前间隔的展示文案。
String get intervalLabel => labelForInterval(_intervalSec);
/// 把间隔秒数翻译成展示文案(设置页的选项弹层也用这一份,避免两处文案走偏)。
static String labelForInterval(int seconds) {
switch (seconds) {
case 30:
return S.t('30 秒');
case 120:
return S.t('2 分钟');
case 300:
return S.t('5 分钟');
default:
return S.t('1 分钟');
}
}
/// 从本地读取设置;若上次开启了监控则自动恢复运行。
Future<void> load() async {
try {
final prefs = await SharedPreferences.getInstance();
_enabled = prefs.getBool(_kEnabled) ?? false;
_notifyOffline = prefs.getBool(_kOffline) ?? true;
_notifyRecovered = prefs.getBool(_kRecovered) ?? true;
_notifyJoin = prefs.getBool(_kJoin) ?? true;
final saved = prefs.getInt(_kInterval) ?? 60;
_intervalSec = intervalOptions.contains(saved) ? saved : 60;
} catch (e) {
debugPrint('读取监控设置失败: $e');
}
if (_enabled) _startTimer();
_notify();
}
Future<void> setEnabled(bool value) async {
if (_enabled == value) return;
_enabled = value;
_notify();
await _persistBool(_kEnabled, value);
if (value) {
_startTimer();
// 开启后立刻检查一次,用户能马上看到效果,不用干等一个周期
await checkNow();
} else {
_timer?.cancel();
_timer = null;
// 关掉后清空快照:下次开启重新建立基线,避免拿旧状态误报离线
_snapshots.clear();
_onlineCount = 0;
_notify();
}
}
Future<void> setNotifyOffline(bool value) async {
_notifyOffline = value;
_notify();
await _persistBool(_kOffline, value);
}
Future<void> setNotifyRecovered(bool value) async {
_notifyRecovered = value;
_notify();
await _persistBool(_kRecovered, value);
}
Future<void> setNotifyJoin(bool value) async {
_notifyJoin = value;
_notify();
await _persistBool(_kJoin, value);
}
Future<void> setInterval(int seconds) async {
if (!intervalOptions.contains(seconds) || seconds == _intervalSec) return;
_intervalSec = seconds;
_notify();
await _persistInt(_kInterval, seconds);
if (_enabled) _startTimer();
}
void _startTimer() {
_timer?.cancel();
_timer = Timer.periodic(
Duration(seconds: _intervalSec),
(_) => checkNow(),
);
}
/// 立即执行一轮检查。
///
/// 每台服务器单独 try/catch:一台超时不能影响其余服务器的检查。
Future<void> checkNow() async {
if (_checking || _disposed) return;
_checking = true;
_notify();
try {
final list = servers.servers;
final seen = <String>{};
var online = 0;
for (final server in list) {
if (_disposed) return;
seen.add(server.id);
try {
final status = await rcon.checkStatus(server);
if (status.online) online++;
await _evaluate(server, status);
} catch (e) {
debugPrint('检查服务器「${server.name}」失败: $e');
}
}
// 已删除的服务器不再保留快照,避免内存里堆积僵尸条目
_snapshots.removeWhere((id, _) => !seen.contains(id));
_onlineCount = online;
_lastCheckAt = DateTime.now();
} finally {
_checking = false;
_notify();
}
}
/// 对比上一轮快照,决定是否需要发通知。
Future<void> _evaluate(ServerConfig server, ServerStatus status) async {
final players = status.online
? parseOnlinePlayerNames(status.playerInfo).toSet()
: <String>{};
final prev = _snapshots[server.id];
if (prev == null) {
// 首次观测:只记基线。否则刚开启监控就会收到「X 进入服务器」的假通知
_snapshots[server.id] = _ServerSnapshot(
online: status.online,
players: players,
);
return;
}
final now = DateTime.now();
final canAlert = prev.lastAlertAt == null ||
now.difference(prev.lastAlertAt!) >= const Duration(minutes: 2);
if (prev.online && !status.online) {
if (_notifyOffline && canAlert) {
await _send(
title: S.t('服务器离线'),
body: S.f('「{0}」已离线,可能已停止运行', <Object>[server.name]),
);
prev.lastAlertAt = now;
}
} else if (!prev.online && status.online) {
if (_notifyRecovered && canAlert) {
await _send(
title: S.t('服务器恢复'),
body: S.f('「{0}」已恢复在线', <Object>[server.name]),
);
prev.lastAlertAt = now;
}
} else if (status.online && _notifyJoin) {
final joined = players.difference(prev.players).toList()..sort();
if (joined.isNotEmpty) {
await _send(
title: S.t('玩家上线'),
body: S.f(
'「{0}」:{1} 进入服务器',
<Object>[server.name, joined.join('、')],
),
);
prev.lastAlertAt = now;
}
}
prev.online = status.online;
prev.players = players;
}
Future<void> _send({required String title, required String body}) async {
await NotificationService.instance.show(
id: ++_notifySeq,
title: title,
body: body,
);
}
void _notify() {
if (_disposed) return;
notifyListeners();
}
Future<void> _persistBool(String key, bool value) async {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(key, value);
} catch (e) {
debugPrint('保存监控设置失败: $e');
}
}
Future<void> _persistInt(String key, int value) async {
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(key, value);
} catch (e) {
debugPrint('保存监控设置失败: $e');
}
}
@override
void dispose() {
_disposed = true;
_timer?.cancel();
_timer = null;
super.dispose();
}
}
+38 -15
View File
@@ -2,37 +2,64 @@ import 'package:flutter/material.dart';
enum AppThemeMode { light, dark, system }
/// 可选主题配色:切换种子色即改变全站强调色与 surface 色调。
enum AppThemeColor {
zl2Green('ZL2 绿', Color(0xFF4CAF50)),
oceanBlue('海蓝', Color(0xFF2196F3)),
violet('星紫', Color(0xFF9C27B0)),
sunsetOrange('暖橙', Color(0xFFFF9800)),
sakuraPink('樱粉', Color(0xFFE91E63));
const AppThemeColor(this.label, this.seed);
final String label;
final Color seed;
}
/// Material 3 主题(参考 ZalithLauncher 的 M3 实现风格):
/// - 用种子色生成完整 tonal palette,强调 colorScheme 的 surface container 层级
/// - 形状体系改用 M3 标准圆角(8 / 12 / 16 / 28),容器类用 16-28 的大圆角
/// - 卡片/列表靠 surfaceContainer 区分层次,弱化描边、不用阴影
class AppTheme {
static const _primaryColor = Color(0xFF4CAF50);
/// 形状体系(对齐 M3 shape scale)
static const radiusXS = 8.0; // 小控件 / chip
static const radiusS = 12.0; // 输入框 / 按钮
static const radiusM = 16.0; // 卡片 / 列表容器
static const radiusL = 28.0; // 弹窗 / 底部面板 / FAB
static ThemeData _base(Brightness brightness) {
/// 默认配色(ZL2 绿)的亮/暗主题:保留 getter,兼容既有调用与官方测试。
static ThemeData get lightTheme => lightThemeFor(AppThemeColor.zl2Green);
static ThemeData get darkTheme => darkThemeFor(AppThemeColor.zl2Green);
/// 按指定配色生成亮/暗主题;切换配色后整棵 widget 树重建即可生效。
static ThemeData lightThemeFor(AppThemeColor color) =>
_base(Brightness.light, color.seed);
static ThemeData darkThemeFor(AppThemeColor color) =>
_base(Brightness.dark, color.seed);
/// 把中性灰按种子色轻微染色,让 surface 层次跟随当前配色。
static Color _tint(Color neutral, Color seed, bool isDark) =>
Color.alphaBlend(seed.withOpacity(isDark ? 0.07 : 0.05), neutral);
static ThemeData _base(Brightness brightness, Color seed) {
final isDark = brightness == Brightness.dark;
Color t(Color n) => _tint(n, seed, isDark);
final scheme = ColorScheme.fromSeed(
seedColor: _primaryColor,
seedColor: seed,
brightness: brightness,
// 让主色更饱和、更接近 ZL2 那种"绿色主色调穿透整个界面"的效果
dynamicSchemeVariant: DynamicSchemeVariant.fidelity,
).copyWith(
surface: isDark ? const Color(0xFF101410) : const Color(0xFFF7FAF5),
surfaceContainerLowest: isDark ? const Color(0xFF0B0E0B) : Colors.white,
surfaceContainerLow: isDark ? const Color(0xFF161A16) : const Color(0xFFF1F5EE),
surfaceContainer: isDark ? const Color(0xFF1B201B) : const Color(0xFFEBF0E8),
surfaceContainerHigh: isDark ? const Color(0xFF232823) : const Color(0xFFE3E9E0),
surfaceContainerHighest: isDark ? const Color(0xFF2C322C) : const Color(0xFFDCE3D9),
surface: isDark ? t(const Color(0xFF101310)) : t(const Color(0xFFF7F9F7)),
surfaceContainerLowest: isDark ? t(const Color(0xFF0B0D0B)) : Colors.white,
surfaceContainerLow: isDark ? t(const Color(0xFF141714)) : t(const Color(0xFFF1F4F1)),
surfaceContainer: isDark ? t(const Color(0xFF1A1D1A)) : t(const Color(0xFFEBEFEB)),
surfaceContainerHigh: isDark ? t(const Color(0xFF222622)) : t(const Color(0xFFE3E8E3)),
surfaceContainerHighest: isDark ? t(const Color(0xFF2A2F2A)) : t(const Color(0xFFDCE2DC)),
);
final cardColor = isDark ? scheme.surfaceContainer : scheme.surfaceContainerLowest;
final outline = isDark ? const Color(0xFF2E352E) : const Color(0xFFDDE4DA);
final outline = isDark ? t(const Color(0xFF2E332E)) : t(const Color(0xFFDDE3DD));
final shapeXS = RoundedRectangleBorder(borderRadius: BorderRadius.circular(radiusXS));
final shapeS = RoundedRectangleBorder(borderRadius: BorderRadius.circular(radiusS));
@@ -263,10 +290,6 @@ class AppTheme {
);
}
static ThemeData get lightTheme => _base(Brightness.light);
static ThemeData get darkTheme => _base(Brightness.dark);
static ThemeMode toFlutterThemeMode(AppThemeMode mode) {
switch (mode) {
case AppThemeMode.light:
+43
View File
@@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../l10n/strings.dart';
import 'update_service.dart';
/// 应用外部链接集中配置。
///
/// 爱发电赞助主页 / 官方 QQ 群一键加群链接;更换地址只需改对应常量。
/// 留空时入口点击会走兜底(提示 / 复制群号),不会跳转到错误页面。
const String kAfdianUrl = 'https://afdian.com/a/ZV-Manager';
/// 打开爱发电赞助页;未配置链接时给出提示,避免跳空。
Future<void> openAfdian(BuildContext context) async {
if (kAfdianUrl.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(S.t('赞助链接待配置'))),
);
return;
}
await UpdateService.openUrl(kAfdianUrl);
}
/// 官方 QQ 群号(兜底:复制后由用户在 QQ 内搜索加群)。
const String kQQGroupNumber = '1104846597';
/// 一键加群链接,由群主在 QQ「群设置 → 分享群 → 复制加群链接」生成,
/// 形如 https://qun.qq.com/join.html?c=... 或 https://qm.qq.com/q/xxx 。
/// QQ 分享链接可能有时效性;失效时把本常量清空即可自动回到「复制群号」兜底。
const String kQQGroupUrl = 'https://qun.qq.com/universal-share/share?ac=1&authKey=dcXyjTs%2FlsBVwuyqft4mtdv0M6%2FneeXoBsSC3NlY64BkPqMQzSMxMwkb7aMSlqvq&busi_data=eyJncm91cENvZGUiOiIxMTA0ODQ2NTk3IiwidG9rZW4iOiJia25JTCsrWGVNTTV1RVR2R291cjV5cGd3dkFQNlpwMHRmSjRYQ1JmVXhIV2VYUkVRTEtTQ0h4dVV6UDRKbndNIiwidWluIjoiMzQ4MDQyODI1MSJ9&data=OOUyy8zBOrBDZJRGvyg3_d-8WmJ8jaEXSFGUfBkjY27G1nJDgzbNHDEU-0c_mFCNfufsWIvaXtwZUOdTL-qZsg&svctype=4&tempid=h5_group_info';
/// 加入官方 QQ 群:优先打开一键加群链接,未配置则复制群号兜底。
Future<void> joinQQGroup(BuildContext context) async {
if (kQQGroupUrl.isNotEmpty) {
await UpdateService.openUrl(kQQGroupUrl);
return;
}
await Clipboard.setData(const ClipboardData(text: kQQGroupNumber));
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(S.t('群号已复制,打开 QQ 搜索加群'))),
);
}
+6 -17
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../l10n/strings.dart';
import 'z_widgets.dart';
class UserAgreementDialog extends StatefulWidget {
final VoidCallback onAgree;
@@ -178,23 +179,11 @@ class _UserAgreementDialogState extends State<UserAgreementDialog> {
: null,
child: Row(
children: [
SizedBox(
width: 24,
height: 24,
child: Checkbox(
value: _isChecked,
onChanged: (_countdown <= 0 && _readToEnd)
? (value) {
setState(() {
_isChecked = value ?? false;
});
}
: null,
activeColor: const Color(0xFF28A745),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
),
),
ZSwitch(
value: _isChecked,
size: 34,
enabled: _countdown <= 0 && _readToEnd,
onChanged: (v) => setState(() => _isChecked = v),
),
const SizedBox(width: 8),
Text(
+89 -15
View File
@@ -18,8 +18,9 @@ import '../../providers/wallpaper_provider.dart';
/// 所有组件都接受 [hasWallpaper],在有自定义壁纸时自动切换为半透明深色
/// 浮层 + 白色文字,保证文字在任意背景下都能读清。
/// ZL2 主色:勾选钮/选中态统一使用的绿色。
const Color kZAccent = Color(0xFF4CAF50);
/// 全站强调色:开关/选中态/徽章统一使用。
/// 由 ThemeProvider 在切换主题配色时同步赋值,所有引用点自动跟随,无需逐处传参。
Color kZAccent = const Color(0xFF4CAF50);
/// ZL2 圆角:分组面板与内部行的圆角。
const double kZRadius = 18.0;
@@ -192,41 +193,114 @@ class ZRow extends StatelessWidget {
}
/// ZL2 式圆形勾选开关:选中为绿底白勾,未选中为描边空心圆。
class ZToggle extends StatelessWidget {
/// 胶囊开关:关闭时灰色轨道 + 白色圆滑块,开启时轨道变为当前主题强调色。
///
/// 参数与原 ZToggle 兼容([size] 作为轨道高度基准、[borderColor] 作为关闭态
/// 轨道色),便于全站平滑替换。[enabled] 为 false 时置灰且不可点击,用于
/// 「跟随系统」开启时联动禁用「深色模式」。
class ZSwitch extends StatelessWidget {
final bool value;
final ValueChanged<bool> onChanged;
/// 直径,设置页用 46,列表行内可用 40。
final double size;
/// 未选中时描边颜色(有壁纸时传白色系)。
final Color? borderColor;
final bool enabled;
const ZToggle({
const ZSwitch({
super.key,
required this.value,
required this.onChanged,
this.size = 46,
this.borderColor,
this.enabled = true,
});
@override
Widget build(BuildContext context) {
final dim = borderColor ?? Colors.white54;
final trackH = (size * 0.7).clamp(22.0, 32.0).toDouble();
final trackW = trackH * 1.7;
final thumb = trackH - 6.0;
final offTrack = (borderColor ??
Theme.of(context).colorScheme.outlineVariant)
.withOpacity(0.32);
final onTrack = enabled ? kZAccent : kZAccent.withOpacity(0.4);
return GestureDetector(
onTap: () => onChanged(!value),
onTap: enabled ? () => onChanged(!value) : null,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
duration: const Duration(milliseconds: 180),
width: trackW,
height: trackH,
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(trackH / 2),
color: value ? onTrack : offTrack,
),
child: AnimatedAlign(
duration: const Duration(milliseconds: 180),
curve: Curves.easeOut,
alignment: value ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
width: thumb,
height: thumb,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.18),
blurRadius: 2,
offset: const Offset(0, 1),
),
],
),
),
),
),
);
}
}
/// 圆形打勾标记:选中为实心圆底白勾,未选中为描边空心圆。
///
/// 与 [ZSwitch] 的滑块开关不同,它表达「选中 / 未选中」的标记语义,
/// 适用于二值状态、单选列表与多选列表。参数与 [ZSwitch] 兼容,
/// 便于直接替换;[enabled] 为 false 时置灰且不响应点击。
class ZCheck extends StatelessWidget {
final bool value;
final ValueChanged<bool>? onChanged;
final double size;
final Color? borderColor;
final bool enabled;
const ZCheck({
super.key,
required this.value,
this.onChanged,
this.size = 26,
this.borderColor,
this.enabled = true,
});
@override
Widget build(BuildContext context) {
final dim = (borderColor ??
Theme.of(context).colorScheme.outlineVariant)
.withOpacity(0.55);
final accent = enabled ? kZAccent : kZAccent.withOpacity(0.4);
return GestureDetector(
onTap: enabled && onChanged != null ? () => onChanged!(!value) : null,
child: AnimatedContainer(
duration: const Duration(milliseconds: 180),
width: size,
height: size,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: value ? kZAccent : Colors.transparent,
border: Border.all(color: value ? kZAccent : dim, width: 2),
color: value ? accent : Colors.transparent,
border: Border.all(color: value ? accent : dim, width: 2),
),
child: value
? Icon(Icons.check, size: size * 0.52, color: Colors.white)
: const SizedBox.shrink(),
? Icon(Icons.check, size: size * 0.62, color: Colors.white)
: null,
),
);
}
+1 -1
View File
@@ -299,7 +299,7 @@ class _ConsolePageState extends State<ConsolePage> {
width: 38,
height: 38,
margin: const EdgeInsets.symmetric(vertical: 6),
decoration: const BoxDecoration(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: kZAccent,
),
+1 -1
View File
@@ -533,7 +533,7 @@ class _EmptyDashboard extends StatelessWidget {
color: kZAccent.withOpacity(0.12),
borderRadius: BorderRadius.circular(26),
),
child: const Icon(Icons.dns_rounded, size: 38, color: kZAccent),
child: Icon(Icons.dns_rounded, size: 38, color: kZAccent),
),
const SizedBox(height: 18),
Text(
@@ -1,5 +1,5 @@
import 'package:flutter/foundation.dart';
import '../../../providers/server_provider.dart';
import '../../providers/server_provider.dart';
/// 跨页签共享的「当前选中服务器」。
/// Dashboard / 模组 / 终端 / 下载上传目标等页签共用此状态。
@@ -339,7 +339,7 @@ class _PlayerListPageState extends State<PlayerListPage> {
if (_selecting)
Text(
S.f('已选 {0} 人', [_selected.length]),
style: const TextStyle(
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: kZAccent,
@@ -411,7 +411,7 @@ class _PlayerRow extends StatelessWidget {
title: player.name,
subtitle: player.uuid.isEmpty ? null : player.uuid,
leading: selecting
? ZToggle(
? ZSwitch(
value: selected,
size: 34,
borderColor: style.subColor,
@@ -146,7 +146,7 @@ class _ServerFormDialogState extends State<ServerFormDialog> {
style: st,
title: 'SSH 连接(可选)',
subtitle: '用于模组插件管理与远程终端',
trailing: ZToggle(
trailing: ZSwitch(
value: _sshEnabled,
onChanged: (v) => setState(() => _sshEnabled = v),
),
+19
View File
@@ -4,6 +4,7 @@ import 'package:provider/provider.dart';
import '../../core/l10n/strings.dart';
import '../../core/utils/update_service.dart';
import '../../core/utils/app_links.dart';
import '../../core/widgets/z_widgets.dart';
import '../../providers/wallpaper_provider.dart';
@@ -100,6 +101,24 @@ class _AboutPageState extends State<AboutPage> {
size: 20, color: st.subColor),
onTap: () => showLicensePage(context: context),
),
ZDivider(style: st),
ZRow(
title: '支持作者 · 爱发电',
subtitle: '通过爱发电支持项目开发',
style: st,
leading: Icon(Icons.favorite_border,
size: 20, color: st.subColor),
onTap: () => openAfdian(context),
),
ZDivider(style: st),
ZRow(
title: '加入官方 QQ 群',
subtitle: '与开发者和其他用户交流',
style: st,
leading: Icon(Icons.group_outlined,
size: 20, color: st.subColor),
onTap: () => joinQQGroup(context),
),
]),
const SizedBox(height: 14),
_SectionLabel('创造者', style: st),
@@ -196,9 +196,9 @@ class _MirrorRow extends StatelessWidget {
title: title,
subtitle: subtitle,
onTap: onTap,
trailing: ZToggle(
trailing: ZCheck(
value: selected,
size: 30,
size: 20,
borderColor: style.subColor,
// 单选:只允许从未选变选中,再点已选项不做取消
onChanged: (_) => onTap(),
+15 -1
View File
@@ -121,15 +121,29 @@ class HelpPage extends StatelessWidget {
'点右上角重复检测按钮重复安装 / 版本冲突的 jar',
],
),
_TutorialPanel(
style: st,
icon: Icons.notifications_active_outlined,
title: '七、状态监控与通知',
steps: const [
'进入「我的」→ 设置 → 「状态监控」,打开总开关',
'首次开启会申请通知权限(Android 13+),请点「允许」,否则提醒会被系统丢弃',
'按需开启「服务器离线 / 服务器恢复 / 玩家上线」三类提醒',
'「检查间隔」可选 30 秒 / 1 / 2 / 5 分钟,间隔越短发现越快、轮询压力越大',
'点「立即检查一次」可手动验证 RCON 配置是否可用',
'提醒依赖 App 进程存活:彻底关闭 App 或被系统省电策略限制时不会推送',
],
),
_TutorialPanel(
style: st,
icon: Icons.help_outline,
title: '七、常见问题',
title: '八、常见问题',
steps: const [
'Q:连接失败?→ 检查防火墙是否放行端口、地址端口是否填对、服务器是否在线',
'Q:控制台能连但模组页提示无 SSH?→ 编辑服务器开启 SSH 并填好账号密码',
'Q:TPS 显示 —?→ 原版服务端不支持 tps 命令,Paper/Purpur 等服务端才支持',
'Q:上传模组后不生效?→ 需要重启服务器',
'Q:开了监控却收不到通知?→ 检查系统是否允许本应用通知、是否开了省电限制',
],
),
],
+2 -2
View File
@@ -237,7 +237,7 @@ class _ServerLogPageState extends State<ServerLogPage> {
subtitle: '每 5 秒重新读取目录列表',
style: st,
leading: Icon(Icons.autorenew, size: 20, color: st.subColor),
trailing: ZToggle(
trailing: ZSwitch(
value: _autoRefresh,
size: 40,
borderColor: st.subColor,
@@ -430,7 +430,7 @@ class _LogViewerPageState extends State<_LogViewerPage> {
label: T('底部'),
),
const SizedBox(width: 6),
ZToggle(
ZSwitch(
value: _autoRefresh,
size: 40,
borderColor: Theme.of(context).colorScheme.onSurfaceVariant,
+271 -17
View File
@@ -6,6 +6,9 @@ import 'dart:io';
import 'package:path_provider/path_provider.dart';
import '../../core/theme/app_theme.dart';
import '../../core/utils/background_service.dart';
import '../../core/utils/app_links.dart';
import '../../core/services/notification_service.dart';
import '../../core/services/server_monitor_service.dart';
import '../../core/widgets/background_widget.dart';
import '../../core/widgets/z_widgets.dart';
import '../../providers/theme_provider.dart';
@@ -146,9 +149,12 @@ class _SettingsPageState extends State<SettingsPage> {
ZSheetRow(
icon: Icons.language,
title: _languageName(m),
trailing: provider.mode == m
? Icon(Icons.check_circle_rounded, color: kZAccent, size: 22)
: Icon(Icons.circle_outlined, color: st.subColor, size: 22),
trailing: ZCheck(
value: provider.mode == m,
size: 22,
borderColor: st.subColor,
onChanged: (_) => Navigator.pop(ctx, m),
),
onTap: () => Navigator.pop(ctx, m),
),
],
@@ -163,6 +169,53 @@ class _SettingsPageState extends State<SettingsPage> {
if (mode != null) await provider.setMode(mode);
}
/// 主题配色选择:5 套种子色,选项以开关呈现。
Future<void> _pickThemeColor() async {
final provider = context.read<ThemeProvider>();
final color = await showDialog<AppThemeColor>(
context: context,
builder: (ctx) {
final st = ZStyle.of(ctx, hasWallpaper: false);
return Dialog(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 8),
child: T('主题配色', style: Theme.of(ctx).textTheme.titleMedium),
),
ZPanel(
style: st,
children: [
for (final c in AppThemeColor.values) ...[
if (c != AppThemeColor.values.first) ZDivider(style: st),
ZSheetRow(
icon: Icons.palette_outlined,
iconColor: c.seed,
title: S.t(c.label),
trailing: ZCheck(
value: provider.themeColor == c,
size: 22,
borderColor: st.subColor,
onChanged: (_) => Navigator.pop(ctx, c),
),
onTap: () => Navigator.pop(ctx, c),
),
],
],
),
],
),
),
);
},
);
if (color != null) await provider.setThemeColor(color);
}
Future<void> _pickVideo() async {
final result = await FilePicker.platform.pickFiles(type: FileType.video);
if (result == null) return;
@@ -254,14 +307,107 @@ class _SettingsPageState extends State<SettingsPage> {
}
}
// ==================== 状态监控 ====================
/// 开启监控前先要通知权限:Android 13+ 没权限时通知会被系统直接丢掉,
/// 用户只会觉得「开了但没反应」,所以这里先要权限、拿不到就明说。
Future<void> _toggleMonitor(bool value) async {
final monitor = context.read<ServerMonitorService>();
if (value) {
final granted = await NotificationService.instance.ensurePermission();
if (!mounted) return;
if (!granted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: T('未获得通知权限,提醒可能无法显示,请到系统设置中允许通知')),
);
}
}
await monitor.setEnabled(value);
}
/// 轮询间隔选择:30 秒 / 1 分钟 / 2 分钟 / 5 分钟。
Future<void> _pickMonitorInterval() async {
final monitor = context.read<ServerMonitorService>();
final selected = await showDialog<int>(
context: context,
builder: (ctx) {
final st = ZStyle.of(ctx, hasWallpaper: false);
return Dialog(
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 8),
child: T('检查间隔', style: Theme.of(ctx).textTheme.titleMedium),
),
ZPanel(
style: st,
children: [
for (final seconds
in ServerMonitorService.intervalOptions) ...[
if (seconds !=
ServerMonitorService.intervalOptions.first)
ZDivider(style: st),
ZSheetRow(
icon: Icons.schedule,
title: ServerMonitorService.labelForInterval(seconds),
trailing: ZCheck(
value: monitor.intervalSec == seconds,
size: 22,
borderColor: st.subColor,
onChanged: (_) => Navigator.pop(ctx, seconds),
),
onTap: () => Navigator.pop(ctx, seconds),
),
],
],
),
],
),
),
);
},
);
if (selected != null) await monitor.setInterval(selected);
}
/// 手动跑一轮检查,验证 RCON 配置是否正确。
Future<void> _runMonitorCheck() async {
final monitor = context.read<ServerMonitorService>();
await monitor.checkNow();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
S.f('检查完成:{0} 台服务器在线', <Object>[monitor.onlineCount]),
),
duration: const Duration(seconds: 2),
),
);
}
/// 最近检查时间的展示文案。
String _lastCheckText(DateTime? at) {
if (at == null) return S.t('尚未检查');
final hh = at.hour.toString().padLeft(2, '0');
final mm = at.minute.toString().padLeft(2, '0');
return S.f('{0}:{1}', <Object>[hh, mm]);
}
// ==================== build ====================
@override
Widget build(BuildContext context) {
final themeProvider = context.watch<ThemeProvider>();
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
final monitor = context.watch<ServerMonitorService>();
final scheme = Theme.of(context).colorScheme;
final st = ZStyle(hasWallpaper: hasWallpaper, scheme: scheme);
final systemIsDark =
MediaQuery.of(context).platformBrightness == Brightness.dark;
return Scaffold(
backgroundColor: hasWallpaper ? Colors.transparent : null,
@@ -274,24 +420,43 @@ class _SettingsPageState extends State<SettingsPage> {
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
children: [
ZPanel(style: st, children: [
// ---------- 外观主题 ----------
// ---------- 外观:双开关 + 配色 ----------
ZRow(
title: '外观主题',
subtitle: '亮色、暗色或跟随系统',
title: '深色模式',
subtitle: themeProvider.followSystem
? '跟随系统开启时由系统决定,关闭后可手动切换'
: '开启后使用暗色界面',
style: st,
trailing: ZSegmentedCircles<AppThemeMode>(
value: themeProvider.themeMode,
onChanged: (m) => themeProvider.setThemeMode(m),
onSurface: st.titleColor,
options: const [
ZCircleOption(value: AppThemeMode.light, icon: Icons.light_mode),
ZCircleOption(value: AppThemeMode.dark, icon: Icons.dark_mode),
ZCircleOption(
value: AppThemeMode.system, icon: Icons.brightness_auto),
],
trailing: ZCheck(
value: themeProvider.darkMode(systemIsDark: systemIsDark),
enabled: !themeProvider.followSystem,
size: 26,
borderColor: st.subColor,
onChanged: (v) => themeProvider.setDarkMode(v),
),
),
ZDivider(style: st),
ZRow(
title: '跟随系统',
subtitle: '随系统的深色 / 浅色设置自动切换',
style: st,
trailing: ZCheck(
value: themeProvider.followSystem,
size: 26,
borderColor: st.subColor,
onChanged: (v) =>
themeProvider.setFollowSystem(v, systemIsDark: systemIsDark),
),
),
ZDivider(style: st),
ZRow(
title: '主题配色',
subtitle: '切换全站强调色与界面色调',
style: st,
value: S.t(themeProvider.themeColor.label),
onTap: _pickThemeColor,
),
ZDivider(style: st),
ZRow(
title: '应用背景',
subtitle: '选择一张图片或一段视频作为应用背景',
@@ -308,8 +473,9 @@ class _SettingsPageState extends State<SettingsPage> {
title: '视频声音',
subtitle: '开启后背景视频将播放声音',
style: st,
trailing: ZToggle(
trailing: ZCheck(
value: _videoSoundEnabled,
size: 26,
borderColor: st.subColor,
onChanged: (value) async {
await BackgroundService.setVideoSound(value);
@@ -353,6 +519,80 @@ class _SettingsPageState extends State<SettingsPage> {
),
]),
const SizedBox(height: 14),
ZPanel(style: st, children: [
// ---------- 状态监控与通知 ----------
ZRow(
title: '状态监控',
subtitle: monitor.enabled
? S.f('每 {0}检查一次 · 最近 {1}', <Object>[
monitor.intervalLabel,
_lastCheckText(monitor.lastCheckAt),
])
: '开启后定时检查服务器状态,并在变化时推送通知',
style: st,
trailing: ZCheck(
value: monitor.enabled,
size: 26,
borderColor: st.subColor,
onChanged: _toggleMonitor,
),
),
ZDivider(style: st),
ZRow(
title: '服务器离线提醒',
subtitle: '服务器掉线时推送系统通知',
style: st,
trailing: ZCheck(
value: monitor.notifyOffline,
enabled: monitor.enabled,
size: 26,
borderColor: st.subColor,
onChanged: monitor.setNotifyOffline,
),
),
ZDivider(style: st),
ZRow(
title: '服务器恢复提醒',
subtitle: '服务器重新上线时推送通知',
style: st,
trailing: ZCheck(
value: monitor.notifyRecovered,
enabled: monitor.enabled,
size: 26,
borderColor: st.subColor,
onChanged: monitor.setNotifyRecovered,
),
),
ZDivider(style: st),
ZRow(
title: '玩家上线提醒',
subtitle: '有新玩家进入服务器时推送通知',
style: st,
trailing: ZCheck(
value: monitor.notifyJoin,
enabled: monitor.enabled,
size: 26,
borderColor: st.subColor,
onChanged: monitor.setNotifyJoin,
),
),
ZDivider(style: st),
ZRow(
title: '检查间隔',
subtitle: '间隔越短发现越快,对服务器的轮询压力也越大',
style: st,
value: monitor.intervalLabel,
onTap: monitor.enabled ? _pickMonitorInterval : null,
),
ZDivider(style: st),
ZRow(
title: monitor.isChecking ? '正在检查…' : '立即检查一次',
subtitle: '手动跑一轮检查,用来确认 RCON 配置是否可用',
style: st,
onTap: monitor.isChecking ? null : _runMonitorCheck,
),
]),
const SizedBox(height: 14),
ZPanel(style: st, children: [
ZRow(
title: '使用教程',
@@ -384,6 +624,20 @@ class _SettingsPageState extends State<SettingsPage> {
MaterialPageRoute(builder: (_) => const AboutPage()),
),
),
ZDivider(style: st),
ZRow(
title: '支持作者 · 爱发电',
subtitle: '通过爱发电支持项目开发',
style: st,
onTap: () => openAfdian(context),
),
ZDivider(style: st),
ZRow(
title: '加入官方 QQ 群',
subtitle: '与开发者和其他用户交流',
style: st,
onTap: () => joinQQGroup(context),
),
]),
],
),
+4 -4
View File
@@ -2,10 +2,10 @@ import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path_provider/path_provider.dart';
import '../../core/services/download_manager.dart';
import '../../core/services/modrinth_api.dart';
import '../../core/services/mirror_service.dart';
import '../../providers/server_provider.dart';
import '../core/services/download_manager.dart';
import '../core/services/modrinth_api.dart';
import '../core/services/mirror_service.dart';
import 'server_provider.dart';
/// 下载中心状态:镜像源选择 + Modrinth 搜索 + 下载队列暴露。
class DownloadProvider extends ChangeNotifier {
+54 -19
View File
@@ -2,37 +2,72 @@ import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../core/theme/app_theme.dart';
/// 主题模式状态:亮色 / 暗色 / 跟随系统,选择结果持久化到本地。
/// 主题状态:亮/暗/跟随系统 + 配色,选择结果持久化到本地。
///
/// 设置页用两个开关表达明暗:
/// - 跟随系统 = 开 → AppThemeMode.system(深色模式开关置灰,显示系统当前亮度)
/// - 跟随系统 = 关 → 深色模式 ? dark : light
class ThemeProvider extends ChangeNotifier {
static const _key = 'app_theme_mode';
static const _keyMode = 'app_theme_mode';
static const _keyColor = 'app_theme_color';
AppThemeMode _themeMode = AppThemeMode.system;
AppThemeColor _themeColor = AppThemeColor.zl2Green;
AppThemeMode get themeMode => _themeMode;
AppThemeColor get themeColor => _themeColor;
/// 转成 MaterialApp 需要的 ThemeMode
ThemeMode get flutterThemeMode => AppTheme.toFlutterThemeMode(_themeMode);
/// 启动时读取上次保存的主题模式。
/// 读不到或值非法(如版本升级后枚举重命名)时回退到「跟随系统」。
/// 开关 1:是否跟随系统
bool get followSystem => _themeMode == AppThemeMode.system;
/// 开关 2:深色模式。跟随系统时反映系统亮度(由 UI 传入 [systemIsDark])。
bool darkMode({bool systemIsDark = false}) =>
followSystem ? systemIsDark : _themeMode == AppThemeMode.dark;
/// 启动时读取上次保存的明暗与配色;读不到或值非法时回退默认值。
Future<void> loadThemeMode() async {
final prefs = await SharedPreferences.getInstance();
final value = prefs.getString(_key);
if (value != null) {
_themeMode = AppThemeMode.values.firstWhere(
(m) => m.name == value,
orElse: () => AppThemeMode.system,
);
notifyListeners();
}
_themeMode = AppThemeMode.values.firstWhere(
(m) => m.name == prefs.getString(_keyMode),
orElse: () => AppThemeMode.system,
);
_themeColor = AppThemeColor.values.firstWhere(
(c) => c.name == prefs.getString(_keyColor),
orElse: () => AppThemeColor.zl2Green,
);
notifyListeners();
}
/// 切换主题模式:先刷新 UI 再异步落盘,避免点击后有明显延迟感。
/// 切换明暗:先刷新 UI 再异步落盘,避免点击后有明显延迟感。
Future<void> setThemeMode(AppThemeMode mode) async {
if (_themeMode != mode) {
_themeMode = mode;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_key, mode.name);
}
if (_themeMode == mode) return;
_themeMode = mode;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyMode, mode.name);
}
/// 切换主题配色。
Future<void> setThemeColor(AppThemeColor color) async {
if (_themeColor == color) return;
_themeColor = color;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyColor, color.name);
}
/// 开关 1:跟随系统。关闭时沿用当前显示的明暗,避免开关跳变。
Future<void> setFollowSystem(bool value, {bool systemIsDark = false}) =>
setThemeMode(value
? AppThemeMode.system
: (darkMode(systemIsDark: systemIsDark)
? AppThemeMode.dark
: AppThemeMode.light));
/// 开关 2:深色模式。在跟随系统下操作会自动切回手动模式。
Future<void> setDarkMode(bool value) =>
setThemeMode(value ? AppThemeMode.dark : AppThemeMode.light);
}