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:
DriftinBlock committed 2026-10-17 19:43:24 +08:00
1 parent 2dc484154d
commit 67ba7d2c83
8 files changed
+1115 -299

No files matched your search

+458
View File
@@ -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;
}
}
+154 -156
View File
@@ -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('添加服务器'),
),
],
),
),
);
+27 -10
View File
@@ -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
+20 -6
View File
@@ -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),