feat: 卡片式服务器列表 + 壁纸切换闪屏修复
- 新增 ServerCard 卡片组件:三层信息结构、在线呼吸状态点、指标胶囊、 编辑/删除收进 PopupMenu,窄屏 ellipsis 防溢出 - 列表状态轮询改为渐进式刷新:仅首次探测显示 loading,之后静默替换, 消除每 5 秒整片跳动的现象 - 背景改为双层交叉淡入:旧图层常驻,新图层 precache 后淡入, 淡入结束才释放旧 VideoPlayerController - 修复 WallpaperProvider 在 app.dart 与 main.dart 中存在两个实例、 hasWallpaper 不同步导致 AppBar 跳色的问题 - 启动时由 main() 预加载结果直接写入 BackgroundWidget.spec,首帧即带壁纸 - 换壁纸时清理旧文件,避免应用目录无限增长 - 新增 test/server_card_test.dart
This commit is contained in:
1 parent
2dc484154d
commit
67ba7d2c83
8 files changed
+1115
-299
No files matched your search
+16
-10
@@ -7,6 +7,7 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'core/theme/app_theme.dart';
|
||||
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 'features/server_list/server_list_page.dart';
|
||||
import 'providers/theme_provider.dart';
|
||||
@@ -16,15 +17,16 @@ import 'providers/server_provider.dart';
|
||||
final navigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
class ZVManagerApp extends StatefulWidget {
|
||||
const ZVManagerApp({super.key});
|
||||
/// 由 main() 传入已预加载的实例,避免在树里重建导致状态不同步。
|
||||
final WallpaperProvider wallpaperProvider;
|
||||
|
||||
const ZVManagerApp({super.key, required this.wallpaperProvider});
|
||||
|
||||
@override
|
||||
State<ZVManagerApp> createState() => ZVManagerAppState();
|
||||
}
|
||||
|
||||
class ZVManagerAppState extends State<ZVManagerApp> {
|
||||
final GlobalKey<BackgroundWidgetState> _bgKey = GlobalKey();
|
||||
|
||||
bool _showAgreement = false;
|
||||
bool _isReady = false;
|
||||
|
||||
@@ -75,16 +77,19 @@ class ZVManagerAppState extends State<ZVManagerApp> {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
void refreshBackground() {
|
||||
_bgKey.currentState?.refreshBackground();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MultiProvider(
|
||||
// 注意:WallpaperProvider 只在 main() 里创建一次(.value 注入),
|
||||
// 不要在这里再 create 一个新的 —— 否则设置页与列表页会各持一份状态,
|
||||
// hasWallpaper 翻转不同步,切换壁纸时 AppBar 会跳一下色。
|
||||
providers: [
|
||||
ChangeNotifierProvider(create: (_) => ThemeProvider()),
|
||||
ChangeNotifierProvider(create: (_) => ServerProvider()),
|
||||
// 复用 main() 中预加载的实例,不能在这里 create 一个新的
|
||||
ChangeNotifierProvider<WallpaperProvider>.value(
|
||||
value: widget.wallpaperProvider,
|
||||
),
|
||||
],
|
||||
child: Consumer<ThemeProvider>(
|
||||
builder: (context, themeProvider, child) {
|
||||
@@ -107,16 +112,17 @@ class ZVManagerAppState extends State<ZVManagerApp> {
|
||||
],
|
||||
home: const ServerListPage(),
|
||||
builder: (context, child) {
|
||||
child ??= const SizedBox.shrink();
|
||||
return BackgroundWidget(
|
||||
key: _bgKey,
|
||||
child: Stack(
|
||||
children: [
|
||||
child!,
|
||||
child,
|
||||
// 新增:用户守则弹窗
|
||||
if (_isReady && _showAgreement)
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
color: Colors.black.withOpacity(0.6),
|
||||
// withOpacity 在新版 Flutter 已废弃,统一用 withValues
|
||||
color: Colors.black.withValues(alpha: 0.6),
|
||||
child: Center(
|
||||
child: UserAgreementDialog(onAgree: _onAgree),
|
||||
),
|
||||
|
||||
@@ -1,174 +1,277 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
|
||||
import '../utils/background_service.dart';
|
||||
|
||||
/// 壁纸描述。可比较,便于 `ValueNotifier` 去重。
|
||||
@immutable
|
||||
class BackgroundSpec {
|
||||
final String? type; // 'image' | 'video' | null
|
||||
final String? path;
|
||||
|
||||
const BackgroundSpec({this.type, this.path});
|
||||
|
||||
const BackgroundSpec.none()
|
||||
: type = null,
|
||||
path = null;
|
||||
|
||||
bool get isEmpty => path == null;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is BackgroundSpec && other.type == type && other.path == path;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(type, path);
|
||||
}
|
||||
|
||||
/// 已解析、可绘制的背景层。
|
||||
class _Layer {
|
||||
final ImageProvider? image;
|
||||
final VideoPlayerController? video;
|
||||
|
||||
const _Layer.image(ImageProvider this.image) : video = null;
|
||||
const _Layer.video(VideoPlayerController this.video) : image = null;
|
||||
|
||||
bool get isVideo => video != null;
|
||||
|
||||
Future<void> dispose() async => video?.dispose();
|
||||
}
|
||||
|
||||
/// 全局壁纸背景。
|
||||
///
|
||||
/// 原实现切壁纸会闪屏,原因有三条,这里逐一解决:
|
||||
///
|
||||
/// 1. `_isLoading` 为 true 时直接返回 child —— 加载期间背景整棵树被换掉,
|
||||
/// 露出主题底色。现在改为「新图层叠在旧图层上」,加载期间旧壁纸照常显示。
|
||||
/// 2. 切换时先清空 `_cachedImage` / 关掉视频,再异步初始化新资源;
|
||||
/// 中间任何一次 setState 都已经丢掉了画面。现在旧图层保持存活,
|
||||
/// 直到新图层首帧绘制完成才淡出并释放。
|
||||
/// 3. 图片未 `precacheImage`,`Image` 首帧为空 —— 即使有旧图层叠加,
|
||||
/// 叠上来的也是一个透明空帧。现在解码完成才参与合成。
|
||||
class BackgroundWidget extends StatefulWidget {
|
||||
final Widget child;
|
||||
|
||||
const BackgroundWidget({super.key, required this.child});
|
||||
|
||||
/// 当前壁纸值。由 `main.dart` 在启动时用 Provider 预加载结果写入,
|
||||
/// 避免「首帧无壁纸、次帧才出现」的启动闪烁。
|
||||
static final ValueNotifier<BackgroundSpec> spec =
|
||||
ValueNotifier<BackgroundSpec>(const BackgroundSpec.none());
|
||||
|
||||
@override
|
||||
State<BackgroundWidget> createState() => BackgroundWidgetState();
|
||||
}
|
||||
|
||||
class BackgroundWidgetState extends State<BackgroundWidget>
|
||||
with WidgetsBindingObserver {
|
||||
VideoPlayerController? _controller;
|
||||
FileImage? _cachedImage;
|
||||
String? _currentType;
|
||||
String? _currentPath;
|
||||
bool _isLoading = true;
|
||||
static const Duration _fadeDuration = Duration(milliseconds: 300);
|
||||
|
||||
/// 已生效的图层。
|
||||
_Layer? _active;
|
||||
String? _activeKey;
|
||||
|
||||
/// 正在淡入的图层。
|
||||
_Layer? _incoming;
|
||||
String? _incomingKey;
|
||||
|
||||
/// 进行中的请求序号,用于丢弃过期结果。
|
||||
int _requestSeq = 0;
|
||||
|
||||
bool _isInForeground = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_loadBackground();
|
||||
_apply(BackgroundWidget.spec.value, animate: false);
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
// 后台时暂停视频,省电 + 减少卡顿
|
||||
if (state == AppLifecycleState.paused) {
|
||||
_isInForeground = false;
|
||||
_controller?.pause();
|
||||
_active?.video?.pause();
|
||||
_incoming?.video?.pause();
|
||||
} else if (state == AppLifecycleState.resumed) {
|
||||
_isInForeground = true;
|
||||
if (_controller != null && _controller!.value.isInitialized) {
|
||||
_controller!.play();
|
||||
}
|
||||
final v = _active?.video;
|
||||
if (v != null && v.value.isInitialized) v.play();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadBackground() async {
|
||||
final data = await BackgroundService.getBackground();
|
||||
final type = data['type'];
|
||||
final path = data['path'];
|
||||
/// 外部入口:按 `spec` 最新值切换壁纸。
|
||||
void refreshBackground() => _apply(BackgroundWidget.spec.value, animate: true);
|
||||
|
||||
// 路径没变,不重新加载
|
||||
if (_currentType == type && _currentPath == path && _controller != null) {
|
||||
if (mounted) setState(() => _isLoading = false);
|
||||
static String _keyOf(BackgroundSpec s) => s.isEmpty ? 'none' : '${s.type}:${s.path}';
|
||||
|
||||
Future<_Layer?> _buildLayer(BackgroundSpec spec) async {
|
||||
if (spec.isEmpty) return null;
|
||||
final file = File(spec.path!);
|
||||
if (!file.existsSync()) return null;
|
||||
|
||||
if (spec.type == 'video') {
|
||||
final sound = await BackgroundService.getVideoSound();
|
||||
final controller = VideoPlayerController.file(file);
|
||||
try {
|
||||
await controller.initialize().timeout(const Duration(seconds: 10));
|
||||
} catch (e) {
|
||||
debugPrint('壁纸视频初始化失败: $e');
|
||||
await controller.dispose();
|
||||
return null;
|
||||
}
|
||||
await controller.setLooping(true);
|
||||
await controller.setVolume(sound ? 1.0 : 0.0);
|
||||
// 停在首帧:淡入完成后再统一播放,避免声音早于画面
|
||||
await controller.seekTo(Duration.zero);
|
||||
return _Layer.video(controller);
|
||||
}
|
||||
|
||||
if (spec.type == 'image') {
|
||||
final provider = FileImage(file);
|
||||
try {
|
||||
// 解码进图片缓存,保证合成上去的第一帧就是完整画面
|
||||
await precacheImage(provider, context);
|
||||
} catch (e) {
|
||||
debugPrint('壁纸图片预加载失败: $e');
|
||||
return null;
|
||||
}
|
||||
return _Layer.image(provider);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<void> _apply(BackgroundSpec spec, {required bool animate}) async {
|
||||
final key = _keyOf(spec);
|
||||
// 同一张壁纸重复设置:忽略,避免无意义的淡入
|
||||
if (key == _activeKey && _incoming == null) return;
|
||||
|
||||
final seq = ++_requestSeq;
|
||||
final layer = await _buildLayer(spec);
|
||||
|
||||
if (!mounted || seq != _requestSeq) {
|
||||
await layer?.dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
// 释放旧视频
|
||||
if (_controller != null) {
|
||||
await _controller!.dispose();
|
||||
_controller = null;
|
||||
// 加载失败(文件丢失、解码失败):保持当前画面不动,不要退回主题底色。
|
||||
// 唯一例外是用户主动清除壁纸(spec 为空),那本来就该回到无背景。
|
||||
if (layer == null && !spec.isEmpty) {
|
||||
debugPrint('壁纸加载失败,保持当前背景: $key');
|
||||
return;
|
||||
}
|
||||
|
||||
_currentType = type;
|
||||
_currentPath = path;
|
||||
_cachedImage = null;
|
||||
|
||||
// ===== 视频背景 =====
|
||||
if (type == 'video' && path != null) {
|
||||
try {
|
||||
final file = File(path);
|
||||
if (!file.existsSync()) {
|
||||
if (mounted) setState(() => _isLoading = false);
|
||||
return;
|
||||
}
|
||||
|
||||
final videoSound = await BackgroundService.getVideoSound();
|
||||
final controller = VideoPlayerController.file(file);
|
||||
|
||||
// 超时保护,避免卡住
|
||||
await controller.initialize().timeout(
|
||||
const Duration(seconds: 10),
|
||||
onTimeout: () {
|
||||
throw Exception('视频初始化超时');
|
||||
},
|
||||
);
|
||||
|
||||
controller.setLooping(true);
|
||||
controller.setVolume(videoSound ? 1.0 : 0.0);
|
||||
if (_isInForeground) controller.play();
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_controller = controller;
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
} catch (e) {
|
||||
debugPrint('视频加载失败: $e');
|
||||
}
|
||||
if (!animate) {
|
||||
final old = _active;
|
||||
setState(() {
|
||||
_active = layer;
|
||||
_activeKey = key;
|
||||
_incoming = null;
|
||||
_incomingKey = null;
|
||||
});
|
||||
await old?.dispose();
|
||||
_startActivePlayback();
|
||||
return;
|
||||
}
|
||||
|
||||
// ===== 图片背景 =====
|
||||
if (type == 'image' && path != null) {
|
||||
final file = File(path);
|
||||
if (file.existsSync()) {
|
||||
_cachedImage = FileImage(file);
|
||||
}
|
||||
}
|
||||
setState(() {
|
||||
_incoming = layer;
|
||||
_incomingKey = key;
|
||||
});
|
||||
|
||||
if (mounted) setState(() => _isLoading = false);
|
||||
// 等新图层真正上屏再开始计时
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
Future<void>.delayed(_fadeDuration, () async {
|
||||
if (!mounted || seq != _requestSeq) return;
|
||||
final old = _active;
|
||||
setState(() {
|
||||
_active = layer;
|
||||
_activeKey = key;
|
||||
_incoming = null;
|
||||
_incomingKey = null;
|
||||
});
|
||||
_startActivePlayback();
|
||||
// 淡出动画走完再释放旧控制器,避免正在播放的视频被提前销毁
|
||||
await Future<void>.delayed(_fadeDuration);
|
||||
await old?.dispose();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// 供外部调用刷新壁纸
|
||||
void refreshBackground() {
|
||||
_loadBackground();
|
||||
void _startActivePlayback() {
|
||||
final v = _active?.video;
|
||||
if (v != null && v.value.isInitialized && _isInForeground) {
|
||||
v.play();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_requestSeq++; // 让在途请求失效
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_controller?.dispose();
|
||||
_active?.dispose();
|
||||
_incoming?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Widget _buildLayerWidget(_Layer layer) {
|
||||
final v = layer.video;
|
||||
if (v != null) {
|
||||
return FittedBox(
|
||||
fit: BoxFit.cover,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
child: SizedBox(
|
||||
width: v.value.size.width,
|
||||
height: v.value.size.height,
|
||||
child: VideoPlayer(v),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Image(
|
||||
image: layer.image!,
|
||||
fit: BoxFit.cover,
|
||||
gaplessPlayback: true,
|
||||
filterQuality: FilterQuality.medium,
|
||||
excludeFromSemantics: true,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// 还在加载,直接显示子组件
|
||||
if (_isLoading) return widget.child;
|
||||
final active = _active;
|
||||
final incoming = _incoming;
|
||||
|
||||
// ===== 视频背景 =====
|
||||
if (_controller != null && _controller!.value.isInitialized) {
|
||||
return RepaintBoundary(
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
SizedBox.expand(
|
||||
child: FittedBox(
|
||||
fit: BoxFit.cover,
|
||||
child: SizedBox(
|
||||
width: _controller!.value.size.width,
|
||||
height: _controller!.value.size.height,
|
||||
child: VideoPlayer(_controller!),
|
||||
),
|
||||
),
|
||||
),
|
||||
Container(color: Colors.black.withOpacity(0.3)),
|
||||
_wrapWithTransparentTheme(widget.child),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (active == null && incoming == null) {
|
||||
return widget.child;
|
||||
}
|
||||
|
||||
// ===== 图片背景 =====
|
||||
if (_cachedImage != null) {
|
||||
return RepaintBoundary(
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Image(
|
||||
image: _cachedImage!,
|
||||
fit: BoxFit.cover,
|
||||
gaplessPlayback: true, // 避免切换时闪白
|
||||
),
|
||||
_wrapWithTransparentTheme(widget.child),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
final showingVideo = (incoming ?? active)!.isVideo;
|
||||
|
||||
// ===== 无背景 =====
|
||||
return widget.child;
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
// 与主题一致的底色,视频有黑边或加载中也不会露白
|
||||
ColoredBox(color: Theme.of(context).scaffoldBackgroundColor),
|
||||
|
||||
// 旧图层常驻,新图层叠上去做交叉淡入
|
||||
if (active != null) _buildLayerWidget(active),
|
||||
if (incoming != null)
|
||||
_FadeIn(
|
||||
key: ValueKey(_incomingKey),
|
||||
duration: _fadeDuration,
|
||||
child: _buildLayerWidget(incoming),
|
||||
),
|
||||
|
||||
if (showingVideo)
|
||||
IgnorePointer(child: ColoredBox(color: Colors.black.withValues(alpha: 0.3))),
|
||||
|
||||
_wrapWithTransparentTheme(widget.child),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _wrapWithTransparentTheme(Widget child) {
|
||||
@@ -179,4 +282,51 @@ class BackgroundWidgetState extends State<BackgroundWidget>
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 从上到下淡入的子层。
|
||||
///
|
||||
/// 注意:不能直接用 `AnimatedOpacity(opacity: 1)` —— 它只在 opacity 属性
|
||||
/// 变化时动画,首次构建即 1 是不会有任何过渡的。这里用显式控制器,
|
||||
/// 在首帧后把 0 → 1,保证新壁纸是「渐渐出现」而不是「啪一下替换」。
|
||||
class _FadeIn extends StatefulWidget {
|
||||
final Widget child;
|
||||
final Duration duration;
|
||||
|
||||
const _FadeIn({
|
||||
super.key,
|
||||
required this.child,
|
||||
required this.duration,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_FadeIn> createState() => _FadeInState();
|
||||
}
|
||||
|
||||
class _FadeInState extends State<_FadeIn> with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _ctrl = AnimationController(
|
||||
vsync: this,
|
||||
duration: widget.duration,
|
||||
);
|
||||
late final Animation<double> _opacity =
|
||||
CurvedAnimation(parent: _ctrl, curve: Curves.easeInOut);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) _ctrl.forward();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ctrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FadeTransition(opacity: _opacity, child: widget.child);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
import 'dart:ui' show FontFeature;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// 服务器卡片的数据状态。
|
||||
enum ServerCardState {
|
||||
/// 尚未完成首次探测。
|
||||
loading,
|
||||
|
||||
/// 在线。
|
||||
online,
|
||||
|
||||
/// 离线(不可达或鉴权失败)。
|
||||
offline,
|
||||
}
|
||||
|
||||
/// 卡片式服务器列表项。
|
||||
///
|
||||
/// 设计要点:
|
||||
/// - 固定高度,横向排版,信息分三层:标题 / 地址 / 指标;
|
||||
/// - 在线态用品牌色描边 + 柔和高光,离线态降饱和但仍保持可读;
|
||||
/// - 操作(编辑 / 删除)收进 `PopupMenuButton`,避免两个 IconButton
|
||||
/// 在窄屏上挤压内容(原实现小屏下地址会被大面积截断)。
|
||||
class ServerCard extends StatelessWidget {
|
||||
final String name;
|
||||
final String host;
|
||||
final int port;
|
||||
final ServerCardState state;
|
||||
final int? playerCount;
|
||||
final int? maxPlayers;
|
||||
final int? latencyMs;
|
||||
final double? tps;
|
||||
|
||||
final VoidCallback onTap;
|
||||
final VoidCallback onEdit;
|
||||
final VoidCallback onDelete;
|
||||
|
||||
const ServerCard({
|
||||
super.key,
|
||||
required this.name,
|
||||
required this.host,
|
||||
required this.port,
|
||||
required this.state,
|
||||
required this.onTap,
|
||||
required this.onEdit,
|
||||
required this.onDelete,
|
||||
this.playerCount,
|
||||
this.maxPlayers,
|
||||
this.latencyMs,
|
||||
this.tps,
|
||||
});
|
||||
|
||||
static const double _radius = 20;
|
||||
|
||||
/// TPS 分档着色:≥16 流畅,≥10 偏低,否则卡顿。
|
||||
static Color tpsColor(double tps) {
|
||||
if (tps >= 16) return const Color(0xFF34D399);
|
||||
if (tps >= 10) return const Color(0xFFFBBF24);
|
||||
return const Color(0xFFF87171);
|
||||
}
|
||||
|
||||
Color get _statusColor {
|
||||
switch (state) {
|
||||
case ServerCardState.online:
|
||||
return const Color(0xFF34D399);
|
||||
case ServerCardState.offline:
|
||||
return const Color(0xFFF87171);
|
||||
case ServerCardState.loading:
|
||||
return const Color(0xFF94A3B8);
|
||||
}
|
||||
}
|
||||
|
||||
String get _statusLabel {
|
||||
switch (state) {
|
||||
case ServerCardState.online:
|
||||
return '在线';
|
||||
case ServerCardState.offline:
|
||||
return '离线';
|
||||
case ServerCardState.loading:
|
||||
return '检测中';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final scheme = theme.colorScheme;
|
||||
final online = state == ServerCardState.online;
|
||||
|
||||
// 卡片底色跟随主题表面色,浮一层极淡的品牌色,避免纯白/纯黑显得生硬。
|
||||
final Color base = Color.alphaBlend(
|
||||
scheme.primary.withValues(alpha: online ? 0.06 : 0.02),
|
||||
scheme.surface,
|
||||
);
|
||||
|
||||
return Semantics(
|
||||
button: true,
|
||||
label: '$name,$_statusLabel',
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: Ink(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(_radius),
|
||||
color: base,
|
||||
border: Border.all(
|
||||
color: online
|
||||
? scheme.primary.withValues(alpha: 0.38)
|
||||
: scheme.outlineVariant.withValues(alpha: 0.55),
|
||||
width: online ? 1.4 : 1,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: online ? 0.08 : 0.04),
|
||||
blurRadius: online ? 18 : 10,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(_radius),
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 8, 14),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildHeader(context, scheme, online),
|
||||
const SizedBox(height: 10),
|
||||
_buildAddress(context, scheme),
|
||||
const SizedBox(height: 12),
|
||||
_buildMetrics(context, scheme),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader(BuildContext context, ColorScheme scheme, bool online) {
|
||||
final theme = Theme.of(context);
|
||||
return Row(
|
||||
children: [
|
||||
_StatusDot(color: _statusColor, pulsing: online),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: -0.2,
|
||||
),
|
||||
),
|
||||
),
|
||||
// 状态胶囊
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: _statusColor.withValues(alpha: 0.13),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: _statusColor.withValues(alpha: 0.28)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_statusLabel,
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: _statusColor,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
if (online && latencyMs != null) ...[
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
'${latencyMs}ms',
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: _statusColor.withValues(alpha: 0.75),
|
||||
fontFeatures: const [FontFeature.tabularFigures()],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
_buildMenu(context, scheme),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMenu(BuildContext context, ColorScheme scheme) {
|
||||
return PopupMenuButton<String>(
|
||||
tooltip: '更多操作',
|
||||
icon: Icon(Icons.more_vert, size: 20, color: scheme.onSurfaceVariant),
|
||||
padding: EdgeInsets.zero,
|
||||
itemBuilder: (context) => [
|
||||
const PopupMenuItem(
|
||||
value: 'edit',
|
||||
height: 44,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.edit_outlined, size: 19),
|
||||
SizedBox(width: 12),
|
||||
Text('编辑'),
|
||||
],
|
||||
),
|
||||
),
|
||||
PopupMenuItem(
|
||||
value: 'delete',
|
||||
height: 44,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.delete_outline, size: 19, color: scheme.error),
|
||||
const SizedBox(width: 12),
|
||||
Text('删除', style: TextStyle(color: scheme.error)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
onSelected: (value) {
|
||||
if (value == 'edit') {
|
||||
onEdit();
|
||||
} else if (value == 'delete') {
|
||||
onDelete();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildAddress(BuildContext context, ColorScheme scheme) {
|
||||
return Row(
|
||||
children: [
|
||||
Icon(Icons.dns_outlined, size: 14, color: scheme.onSurfaceVariant),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'$host:$port',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
letterSpacing: 0.1,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMetrics(BuildContext context, ColorScheme scheme) {
|
||||
final online = state == ServerCardState.online;
|
||||
|
||||
if (state == ServerCardState.loading) {
|
||||
return _pillRow(context, [
|
||||
const _Pill(
|
||||
icon: Icons.autorenew_rounded,
|
||||
label: '正在获取状态',
|
||||
color: Color(0xFF94A3B8),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
if (!online) {
|
||||
return Row(
|
||||
children: [
|
||||
const Flexible(
|
||||
child: _Pill(
|
||||
icon: Icons.cloud_off_outlined,
|
||||
label: '无法连接',
|
||||
color: Color(0xFFF87171),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
'点击重试',
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
Icon(Icons.refresh_rounded, size: 15, color: scheme.onSurfaceVariant),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final pills = <Widget>[
|
||||
_Pill(
|
||||
icon: Icons.people_alt_outlined,
|
||||
label: maxPlayers != null
|
||||
? '${playerCount ?? 0}/$maxPlayers'
|
||||
: '${playerCount ?? 0} 人',
|
||||
color: scheme.primary,
|
||||
emphasized: true,
|
||||
),
|
||||
];
|
||||
|
||||
final tpsValue = tps;
|
||||
if (tpsValue != null) {
|
||||
pills.add(_Pill(
|
||||
icon: Icons.speed_rounded,
|
||||
label: 'TPS ${tpsValue.toStringAsFixed(1)}',
|
||||
color: tpsColor(tpsValue),
|
||||
));
|
||||
}
|
||||
|
||||
return _pillRow(
|
||||
context,
|
||||
pills,
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'进入控制台',
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: scheme.primary,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
Icon(Icons.chevron_right, size: 16, color: scheme.primary),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _pillRow(BuildContext context, List<Widget> pills, {Widget? trailing}) {
|
||||
return Row(
|
||||
children: [
|
||||
for (var i = 0; i < pills.length; i++) ...[
|
||||
if (i > 0) const SizedBox(width: 8),
|
||||
Flexible(child: pills[i]),
|
||||
],
|
||||
const Spacer(),
|
||||
if (trailing != null) trailing,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 状态圆点:在线时带柔和呼吸光晕。
|
||||
class _StatusDot extends StatefulWidget {
|
||||
final Color color;
|
||||
final bool pulsing;
|
||||
const _StatusDot({required this.color, required this.pulsing});
|
||||
|
||||
@override
|
||||
State<_StatusDot> createState() => _StatusDotState();
|
||||
}
|
||||
|
||||
class _StatusDotState extends State<_StatusDot>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _ctrl = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1800),
|
||||
);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (widget.pulsing) _ctrl.repeat(reverse: true);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _StatusDot old) {
|
||||
super.didUpdateWidget(old);
|
||||
if (widget.pulsing && !_ctrl.isAnimating) {
|
||||
_ctrl.repeat(reverse: true);
|
||||
} else if (!widget.pulsing && _ctrl.isAnimating) {
|
||||
_ctrl.stop();
|
||||
_ctrl.value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ctrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: _ctrl,
|
||||
builder: (context, _) {
|
||||
final glow = widget.pulsing ? 0.18 + 0.16 * _ctrl.value : 0.0;
|
||||
return Container(
|
||||
width: 10,
|
||||
height: 10,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: widget.color,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: widget.color.withValues(alpha: glow),
|
||||
blurRadius: 10,
|
||||
spreadRadius: 3,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 指标胶囊。
|
||||
class _Pill extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final Color color;
|
||||
final bool emphasized;
|
||||
|
||||
const _Pill({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.color,
|
||||
this.emphasized = false,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bg = emphasized
|
||||
? color.withValues(alpha: 0.14)
|
||||
: color.withValues(alpha: 0.08);
|
||||
|
||||
final content = Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
|
||||
decoration: BoxDecoration(
|
||||
color: bg,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 13, color: color),
|
||||
const SizedBox(width: 5),
|
||||
Flexible(
|
||||
child: Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: color,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontFeatures: const [FontFeature.tabularFigures()],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
return content;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import '../../providers/server_provider.dart';
|
||||
import '../../providers/wallpaper_provider.dart';
|
||||
import '../console/console_page.dart';
|
||||
import '../settings/settings_page.dart';
|
||||
import 'server_card.dart';
|
||||
import 'server_form_dialog.dart';
|
||||
|
||||
class ServerListPage extends StatefulWidget {
|
||||
@@ -19,6 +20,7 @@ class ServerListPage extends StatefulWidget {
|
||||
class _ServerListPageState extends State<ServerListPage> {
|
||||
Timer? _pollTimer;
|
||||
final Map<String, ServerStatus> _statusCache = {};
|
||||
final Set<String> _pending = {};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -35,17 +37,39 @@ class _ServerListPageState extends State<ServerListPage> {
|
||||
|
||||
Future<void> _refreshAll() async {
|
||||
final servers = context.read<ServerProvider>().servers;
|
||||
for (final server in servers) {
|
||||
if (!mounted) return;
|
||||
unawaited(_checkStatus(server));
|
||||
}
|
||||
if (mounted) setState(() {});
|
||||
await Future.wait(servers.map(_checkStatus));
|
||||
}
|
||||
|
||||
/// 查询单台服务器状态。
|
||||
///
|
||||
/// 只在「首次查询」时进入 loading 态;后续轮询静默替换结果,
|
||||
/// 避免每 5 秒整列表闪一下 loading。
|
||||
Future<void> _checkStatus(ServerConfig server) async {
|
||||
final status = await context.read<RconProvider>().checkStatus(server);
|
||||
if (!mounted) return;
|
||||
setState(() => _statusCache[server.id] = status);
|
||||
final id = server.id;
|
||||
if (_pending.contains(id)) return;
|
||||
|
||||
// 首次查询才显示 loading;已有结果时静默刷新,不打断阅读
|
||||
if (!_statusCache.containsKey(id) && mounted) {
|
||||
setState(() => _pending.add(id));
|
||||
} else {
|
||||
_pending.add(id);
|
||||
}
|
||||
|
||||
try {
|
||||
final status = await context.read<RconProvider>().checkStatus(server);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_statusCache[id] = status;
|
||||
_pending.remove(id);
|
||||
});
|
||||
} catch (_) {
|
||||
// checkStatus 内部已捕获异常,这里兜底,保证卡片不会永远停在 loading
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_statusCache[id] = ServerStatus(online: false);
|
||||
_pending.remove(id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 打开控制台:已连接直接进入;否则展示「正在连接」,失败则提示连接失败。
|
||||
@@ -109,15 +133,66 @@ class _ServerListPageState extends State<ServerListPage> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 计算卡片状态:无缓存且未在请求中 -> loading;有缓存 -> online/offline。
|
||||
ServerCardState _cardStateOf(String id, ServerStatus? status) {
|
||||
if (_pending.contains(id)) return ServerCardState.loading;
|
||||
if (status == null) return ServerCardState.loading;
|
||||
return status.online ? ServerCardState.online : ServerCardState.offline;
|
||||
}
|
||||
|
||||
Future<void> _addServer() async {
|
||||
final server = await showDialog<ServerConfig>(
|
||||
context: context,
|
||||
builder: (_) => const ServerFormDialog(),
|
||||
);
|
||||
if (server == null || !mounted) return;
|
||||
await context.read<ServerProvider>().addServer(server);
|
||||
if (mounted) unawaited(_checkStatus(server));
|
||||
}
|
||||
|
||||
Future<void> _editServer(ServerConfig server) async {
|
||||
final updated = await showDialog<ServerConfig>(
|
||||
context: context,
|
||||
builder: (_) => ServerFormDialog(existingServer: server),
|
||||
);
|
||||
if (updated == null || !mounted) return;
|
||||
await context.read<ServerProvider>().updateServer(updated);
|
||||
if (mounted) unawaited(_checkStatus(updated));
|
||||
}
|
||||
|
||||
Future<void> _deleteServer(ServerConfig server) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
title: const Text('确认删除'),
|
||||
content: Text('确定要删除服务器「${server.name}」吗?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('删除', style: TextStyle(color: Colors.red)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !mounted) return;
|
||||
final rconProvider = context.read<RconProvider>();
|
||||
await context.read<ServerProvider>().removeServer(server.id);
|
||||
rconProvider.disposeServer(server.id);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final servers = context.watch<ServerProvider>().servers;
|
||||
final theme = Theme.of(context);
|
||||
final hasWallpaper = context.watch<WallpaperProvider>().hasWallpaper;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('MCServer Manager'),
|
||||
title: const Text('ZV Manager'),
|
||||
backgroundColor: hasWallpaper ? Colors.transparent : null,
|
||||
elevation: hasWallpaper ? 0 : null,
|
||||
actions: [
|
||||
@@ -132,170 +207,93 @@ class _ServerListPageState extends State<ServerListPage> {
|
||||
],
|
||||
),
|
||||
body: servers.isEmpty
|
||||
? Center(child: Text('暂无服务器,点击 + 添加', style: theme.textTheme.bodyLarge))
|
||||
? _EmptyState(onAdd: _addServer)
|
||||
: RefreshIndicator(
|
||||
onRefresh: _refreshAll,
|
||||
child: ListView.separated(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.fromLTRB(14, 8, 14, 96),
|
||||
itemCount: servers.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 8),
|
||||
itemBuilder: (_, i) => _ServerCard(
|
||||
server: servers[i],
|
||||
status: _statusCache[servers[i].id],
|
||||
onTap: () => _openConsole(servers[i]),
|
||||
onEdit: () async {
|
||||
final updated = await showDialog<ServerConfig>(
|
||||
context: context,
|
||||
builder: (_) => ServerFormDialog(existingServer: servers[i]),
|
||||
);
|
||||
if (updated != null && context.mounted) {
|
||||
await context.read<ServerProvider>().updateServer(updated);
|
||||
}
|
||||
},
|
||||
onDelete: () async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
title: const Text('确认删除'),
|
||||
content: Text('确定要删除服务器「${servers[i].name}」吗?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('删除', style: TextStyle(color: Colors.red)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed == true && context.mounted) {
|
||||
final id = servers[i].id;
|
||||
final rconProvider = context.read<RconProvider>();
|
||||
await context.read<ServerProvider>().removeServer(id);
|
||||
rconProvider.disposeServer(id);
|
||||
}
|
||||
},
|
||||
),
|
||||
itemBuilder: (_, i) {
|
||||
final server = servers[i];
|
||||
final status = _statusCache[server.id];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: ServerCard(
|
||||
// key 绑定服务器 id:增删改后卡片状态不会错位到别的服务器
|
||||
key: ValueKey(server.id),
|
||||
name: server.name,
|
||||
host: server.host,
|
||||
port: server.port,
|
||||
state: _cardStateOf(server.id, status),
|
||||
playerCount: status?.playerCount,
|
||||
latencyMs: status?.latencyMs,
|
||||
tps: status?.tps,
|
||||
onTap: () => _openConsole(server),
|
||||
onEdit: () => _editServer(server),
|
||||
onDelete: () => _deleteServer(server),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: () async {
|
||||
final server = await showDialog<ServerConfig>(
|
||||
context: context,
|
||||
builder: (_) => const ServerFormDialog(),
|
||||
);
|
||||
if (server != null && context.mounted) {
|
||||
await context.read<ServerProvider>().addServer(server);
|
||||
}
|
||||
},
|
||||
child: const Icon(Icons.add),
|
||||
floatingActionButton: FloatingActionButton.extended(
|
||||
onPressed: _addServer,
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('添加服务器'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- 以下内部类保持不变 ---
|
||||
|
||||
class _ServerCard extends StatelessWidget {
|
||||
final ServerConfig server;
|
||||
final ServerStatus? status;
|
||||
final VoidCallback onTap;
|
||||
final VoidCallback onEdit;
|
||||
final VoidCallback onDelete;
|
||||
|
||||
const _ServerCard({
|
||||
required this.server,
|
||||
required this.status,
|
||||
required this.onTap,
|
||||
required this.onEdit,
|
||||
required this.onDelete,
|
||||
});
|
||||
|
||||
/// 根据 TPS 值返回状态颜色:≥16 流畅(绿),≥10 略低(橙),否则卡顿(红)。
|
||||
static Color _tpsColor(double tps) {
|
||||
if (tps >= 16) return Colors.green;
|
||||
if (tps >= 10) return Colors.orange;
|
||||
return Colors.red;
|
||||
}
|
||||
/// 空列表引导。
|
||||
class _EmptyState extends StatelessWidget {
|
||||
final VoidCallback onAdd;
|
||||
const _EmptyState({required this.onAdd});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final isOnline = status?.online ?? false;
|
||||
|
||||
return Card(
|
||||
elevation: isOnline ? 2 : 0.5,
|
||||
color: isOnline ? null : theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 12,
|
||||
height: 12,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isOnline ? Colors.greenAccent : Colors.redAccent,
|
||||
boxShadow: isOnline
|
||||
? [BoxShadow(color: Colors.greenAccent.withValues(alpha: 0.4), blurRadius: 6)]
|
||||
: null,
|
||||
final scheme = theme.colorScheme;
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 84,
|
||||
height: 84,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: scheme.primary.withValues(alpha: 0.08),
|
||||
border: Border.all(
|
||||
color: scheme.primary.withValues(alpha: 0.18),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(server.name, style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 4),
|
||||
Text('${server.host}:${server.port}', style: theme.textTheme.bodySmall),
|
||||
if (isOnline && status != null) ...[
|
||||
const SizedBox(height: 2),
|
||||
Row(
|
||||
children: [
|
||||
Text('${status!.latencyMs}ms',
|
||||
style: theme.textTheme.labelSmall?.copyWith(color: Colors.green)),
|
||||
if (status!.tps != null) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text('TPS ${status!.tps!.toStringAsFixed(1)}',
|
||||
style: theme.textTheme.labelSmall?.copyWith(color: _tpsColor(status!.tps!))),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
child: Icon(Icons.dns_outlined, size: 36, color: scheme.primary),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
'还没有添加服务器',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
if (isOnline)
|
||||
Chip(
|
||||
label: Text('在线${status?.playerCount ?? 0}人'),
|
||||
visualDensity: VisualDensity.compact,
|
||||
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
)
|
||||
else
|
||||
Chip(
|
||||
label: const Text('离线'),
|
||||
backgroundColor: theme.colorScheme.errorContainer,
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
IconButton(
|
||||
icon: Icon(Icons.edit_outlined, color: theme.colorScheme.primary),
|
||||
tooltip: '编辑服务器',
|
||||
onPressed: onEdit,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'填入主机地址与 RCON 密码,即可在手机上管理',
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: scheme.onSurfaceVariant,
|
||||
),
|
||||
IconButton(
|
||||
icon: Icon(Icons.delete_outline, color: theme.colorScheme.error),
|
||||
tooltip: '删除服务器',
|
||||
onPressed: onDelete,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
FilledButton.icon(
|
||||
onPressed: onAdd,
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('添加服务器'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -9,7 +9,7 @@ import '../../core/theme/app_theme.dart';
|
||||
import '../../core/utils/update_service.dart';
|
||||
import '../../core/utils/background_service.dart';
|
||||
import '../../providers/theme_provider.dart';
|
||||
import '../../app.dart';
|
||||
import '../../providers/wallpaper_provider.dart';
|
||||
|
||||
class SettingsPage extends StatefulWidget {
|
||||
const SettingsPage({super.key});
|
||||
@@ -125,7 +125,9 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
final path = await _saveFileToAssets(result.path, 'image');
|
||||
if (path == null) return;
|
||||
|
||||
await BackgroundService.setBackground('image', path);
|
||||
if (!mounted) return;
|
||||
// 通过 Provider 落盘并通知,背景层随之交叉淡入
|
||||
await context.read<WallpaperProvider>().setCustomWallpaper(path, type: 'image');
|
||||
_refreshUI();
|
||||
}
|
||||
|
||||
@@ -139,7 +141,8 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
final path = await _saveFileToAssets(filePath, 'video');
|
||||
if (path == null) return;
|
||||
|
||||
await BackgroundService.setBackground('video', path);
|
||||
if (!mounted) return;
|
||||
await context.read<WallpaperProvider>().setCustomWallpaper(path, type: 'video');
|
||||
_refreshUI();
|
||||
}
|
||||
|
||||
@@ -153,6 +156,9 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
final file = File(sourcePath);
|
||||
await file.copy(destPath);
|
||||
|
||||
// 换壁纸时清掉上一份(图片与视频都清),否则应用目录会无限膨胀
|
||||
await _cleanupOldBackgrounds(dir.path, keep: destPath);
|
||||
|
||||
return destPath;
|
||||
} catch (e) {
|
||||
print('保存失败: $e');
|
||||
@@ -165,14 +171,30 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 删除应用目录下除 [keep] 之外的旧壁纸文件。
|
||||
Future<void> _cleanupOldBackgrounds(String dirPath, {required String keep}) async {
|
||||
try {
|
||||
final dir = Directory(dirPath);
|
||||
if (!dir.existsSync()) return;
|
||||
await for (final entity in dir.list()) {
|
||||
if (entity is! File) continue;
|
||||
final name = entity.path.split(Platform.pathSeparator).last;
|
||||
if (!name.startsWith('background_')) continue;
|
||||
if (entity.path == keep) continue;
|
||||
await entity.delete();
|
||||
}
|
||||
} catch (_) {
|
||||
// 清理失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _clearBackground() async {
|
||||
await BackgroundService.clearBackground();
|
||||
await context.read<WallpaperProvider>().resetWallpaper();
|
||||
_refreshUI();
|
||||
}
|
||||
|
||||
void _refreshUI() {
|
||||
_loadCurrentBg();
|
||||
_refreshBackground();
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
@@ -184,11 +206,6 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
}
|
||||
}
|
||||
|
||||
void _refreshBackground() {
|
||||
final appState = context.findAncestorStateOfType<ZVManagerAppState>();
|
||||
appState?.refreshBackground();
|
||||
}
|
||||
|
||||
// ==================== build ====================
|
||||
|
||||
@override
|
||||
|
||||
@@ -4,7 +4,6 @@ import 'package:image_picker/image_picker.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'dart:io';
|
||||
import '../../providers/wallpaper_provider.dart';
|
||||
import '../../app.dart';
|
||||
|
||||
class WallpaperSettings extends StatelessWidget {
|
||||
const WallpaperSettings({super.key});
|
||||
@@ -73,9 +72,10 @@ class WallpaperSettings extends StatelessWidget {
|
||||
if (image != null && context.mounted) {
|
||||
final savedPath = await _saveFileToAssets(context, image.path);
|
||||
if (savedPath != null && context.mounted) {
|
||||
// Provider 变更会同步到 BackgroundWidget.spec,
|
||||
// 背景层自己完成交叉淡入,这里不再需要手动刷新
|
||||
await provider.setCustomWallpaper(savedPath);
|
||||
if (context.mounted) {
|
||||
_refreshBackground(context);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('壁纸已更新'), backgroundColor: Colors.green),
|
||||
);
|
||||
@@ -124,6 +124,9 @@ class WallpaperSettings extends StatelessWidget {
|
||||
final file = File(sourcePath);
|
||||
await file.copy(destPath);
|
||||
|
||||
// 清理旧壁纸,避免每次换图都在应用目录留一份副本
|
||||
await _cleanupOldWallpapers(dir.path, keep: destPath);
|
||||
|
||||
return destPath;
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
@@ -135,9 +138,21 @@ class WallpaperSettings extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
void _refreshBackground(BuildContext context) {
|
||||
final appState = context.findAncestorStateOfType<ZVManagerAppState>();
|
||||
appState?.refreshBackground();
|
||||
/// 删除应用目录下除 [keep] 之外的壁纸文件。
|
||||
Future<void> _cleanupOldWallpapers(String dirPath, {required String keep}) async {
|
||||
try {
|
||||
final dir = Directory(dirPath);
|
||||
if (!dir.existsSync()) return;
|
||||
await for (final entity in dir.list()) {
|
||||
if (entity is! File) continue;
|
||||
final name = entity.path.split(Platform.pathSeparator).last;
|
||||
if (!name.startsWith('background_image_')) continue;
|
||||
if (entity.path == keep) continue;
|
||||
await entity.delete();
|
||||
}
|
||||
} catch (_) {
|
||||
// 清理失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
void _showResetDialog(BuildContext context, WallpaperProvider provider) {
|
||||
@@ -155,7 +170,6 @@ class WallpaperSettings extends StatelessWidget {
|
||||
onPressed: () async {
|
||||
await provider.resetWallpaper();
|
||||
if (context.mounted) {
|
||||
_refreshBackground(context);
|
||||
Navigator.pop(context);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('已恢复默认壁纸'), backgroundColor: Colors.green),
|
||||
|
||||
+19
-3
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'app.dart';
|
||||
import 'core/widgets/background_widget.dart';
|
||||
import 'providers/rcon_provider.dart';
|
||||
import 'providers/server_provider.dart';
|
||||
import 'providers/theme_provider.dart';
|
||||
@@ -16,8 +17,23 @@ void main() async {
|
||||
await themeProvider.loadThemeMode();
|
||||
|
||||
// 预加载壁纸设置
|
||||
final wallpaperProvider = WallpaperProvider(); // 新增
|
||||
await wallpaperProvider.loadWallpaper(); // 新增
|
||||
final wallpaperProvider = WallpaperProvider();
|
||||
await wallpaperProvider.loadWallpaper();
|
||||
|
||||
// 把预加载结果直接交给 BackgroundWidget,让首帧就带上壁纸。
|
||||
// 若交给组件自己异步读 SharedPreferences,会出现「无背景一帧」的启动闪屏。
|
||||
BackgroundWidget.spec.value = BackgroundSpec(
|
||||
type: wallpaperProvider.wallpaperType,
|
||||
path: wallpaperProvider.wallpaperPath,
|
||||
);
|
||||
|
||||
// 之后所有壁纸变更都通过 spec 通知背景层,组件内部完成交叉淡入
|
||||
wallpaperProvider.addListener(() {
|
||||
BackgroundWidget.spec.value = BackgroundSpec(
|
||||
type: wallpaperProvider.wallpaperType,
|
||||
path: wallpaperProvider.wallpaperPath,
|
||||
);
|
||||
});
|
||||
|
||||
runApp(
|
||||
MultiProvider(
|
||||
@@ -27,7 +43,7 @@ void main() async {
|
||||
ChangeNotifierProvider(create: (_) => RconProvider()),
|
||||
ChangeNotifierProvider.value(value: wallpaperProvider), // 新增
|
||||
],
|
||||
child: const ZVManagerApp(), // 改成 ZVManagerApp
|
||||
child: ZVManagerApp(wallpaperProvider: wallpaperProvider),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:zv_manager/core/widgets/background_widget.dart';
|
||||
import 'package:zv_manager/features/server_list/server_card.dart';
|
||||
|
||||
Widget _host(Widget child) => MaterialApp(
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
|
||||
void main() {
|
||||
group('ServerCard', () {
|
||||
testWidgets('在线态展示名称、地址、人数与 TPS', (tester) async {
|
||||
await tester.pumpWidget(_host(
|
||||
ServerCard(
|
||||
name: '生存服',
|
||||
host: 'play.example.cn',
|
||||
port: 25575,
|
||||
state: ServerCardState.online,
|
||||
playerCount: 18,
|
||||
latencyMs: 42,
|
||||
tps: 19.8,
|
||||
onTap: () {},
|
||||
onEdit: () {},
|
||||
onDelete: () {},
|
||||
),
|
||||
));
|
||||
|
||||
expect(find.text('生存服'), findsOneWidget);
|
||||
expect(find.text('play.example.cn:25575'), findsOneWidget);
|
||||
// 服务器未下发 max like,展示「18 人」
|
||||
expect(find.textContaining('18'), findsWidgets);
|
||||
expect(find.text('TPS 19.8'), findsOneWidget);
|
||||
expect(find.text('在线'), findsOneWidget);
|
||||
expect(find.text('42ms'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('离线态不显示 TPS,显示无法连接', (tester) async {
|
||||
await tester.pumpWidget(_host(
|
||||
ServerCard(
|
||||
name: '测试服',
|
||||
host: '127.0.0.1',
|
||||
port: 25575,
|
||||
state: ServerCardState.offline,
|
||||
onTap: () {},
|
||||
onEdit: () {},
|
||||
onDelete: () {},
|
||||
),
|
||||
));
|
||||
|
||||
expect(find.text('离线'), findsOneWidget);
|
||||
expect(find.text('无法连接'), findsOneWidget);
|
||||
expect(find.textContaining('TPS'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('检测中显示 loading 文案', (tester) async {
|
||||
await tester.pumpWidget(_host(
|
||||
ServerCard(
|
||||
name: '新服务器',
|
||||
host: '10.0.0.2',
|
||||
port: 25575,
|
||||
state: ServerCardState.loading,
|
||||
onTap: () {},
|
||||
onEdit: () {},
|
||||
onDelete: () {},
|
||||
),
|
||||
));
|
||||
|
||||
expect(find.text('正在获取状态'), findsOneWidget);
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
});
|
||||
|
||||
testWidgets('长名称不溢出(窄屏)', (tester) async {
|
||||
tester.view.physicalSize = const Size(320, 640);
|
||||
tester.view.devicePixelRatio = 1.0;
|
||||
addTearDown(tester.view.reset);
|
||||
|
||||
await tester.pumpWidget(_host(
|
||||
ServerCard(
|
||||
name: '这是一个特别特别长的服务器名称用来测试截断是否正常工作',
|
||||
host: 'a-very-long-subdomain.example-minecraft-server.cn',
|
||||
port: 25575,
|
||||
state: ServerCardState.online,
|
||||
playerCount: 3,
|
||||
latencyMs: 120,
|
||||
tps: 20,
|
||||
onTap: () {},
|
||||
onEdit: () {},
|
||||
onDelete: () {},
|
||||
),
|
||||
));
|
||||
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('菜单可打开编辑与删除', (tester) async {
|
||||
var edited = false;
|
||||
var deleted = false;
|
||||
|
||||
await tester.pumpWidget(_host(
|
||||
ServerCard(
|
||||
name: 'A',
|
||||
host: 'h',
|
||||
port: 1,
|
||||
state: ServerCardState.online,
|
||||
onTap: () {},
|
||||
onEdit: () => edited = true,
|
||||
onDelete: () => deleted = true,
|
||||
),
|
||||
));
|
||||
|
||||
await tester.tap(find.byIcon(Icons.more_vert));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('编辑'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(edited, isTrue);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.more_vert));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('删除'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(deleted, isTrue);
|
||||
});
|
||||
|
||||
test('TPS 分档着色边界', () {
|
||||
expect(ServerCard.tpsColor(16), const Color(0xFF34D399));
|
||||
expect(ServerCard.tpsColor(15.9), const Color(0xFFFBBF24));
|
||||
expect(ServerCard.tpsColor(10), const Color(0xFFFBBF24));
|
||||
expect(ServerCard.tpsColor(9.9), const Color(0xFFF87171));
|
||||
});
|
||||
});
|
||||
|
||||
group('BackgroundSpec', () {
|
||||
test('值相等语义:同路径同类型视为相等', () {
|
||||
const a = BackgroundSpec(type: 'image', path: '/x/1.jpg');
|
||||
const b = BackgroundSpec(type: 'image', path: '/x/1.jpg');
|
||||
const c = BackgroundSpec(type: 'image', path: '/x/2.jpg');
|
||||
expect(a, b);
|
||||
expect(a == c, isFalse);
|
||||
expect(const BackgroundSpec.none().isEmpty, isTrue);
|
||||
expect(a.isEmpty, isFalse);
|
||||
});
|
||||
|
||||
test('ValueNotifier 对相同值不重复通知', () {
|
||||
final notifier = BackgroundWidget.spec;
|
||||
var calls = 0;
|
||||
void listener() => calls++;
|
||||
notifier.addListener(listener);
|
||||
|
||||
notifier.value = const BackgroundSpec(type: 'image', path: '/a.jpg');
|
||||
notifier.value = const BackgroundSpec(type: 'image', path: '/a.jpg');
|
||||
|
||||
expect(calls, 1);
|
||||
notifier.removeListener(listener);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user