webdav存在自引用问题,现版本修复完成

This commit is contained in:
2026-08-17 22:24:56 +08:00
parent 457a9bf1e5
commit a6056c7f1a
5 changed files with 874 additions and 622 deletions
+192 -122
View File
@@ -5,11 +5,12 @@ import '../services/audio_service.dart';
import '../services/webdav_service.dart'; import '../services/webdav_service.dart';
import '../services/playback_service.dart'; import '../services/playback_service.dart';
import '../widgets/mini_player_bar.dart'; import '../widgets/mini_player_bar.dart';
import '../widgets/magnetic_scroll_physics.dart';
import 'webdav_setup_page.dart'; import 'webdav_setup_page.dart';
import 'webdav_file_list_page.dart'; import 'webdav_file_list_page.dart';
// ================================================== // ==================================================
// 歌曲数据模型(含元数据状态) // 歌曲数据模型
// ================================================== // ==================================================
class SongItem { class SongItem {
final String path; final String path;
@@ -17,7 +18,7 @@ class SongItem {
final String? title; final String? title;
final String? artist; final String? artist;
final String sourceTag; final String sourceTag;
final String metadataState; // "unknown" | "loading" | "success" | "failed" final String metadataState;
SongItem({ SongItem({
required this.path, required this.path,
@@ -42,7 +43,7 @@ class SongItem {
} }
// ================================================== // ==================================================
// 通用可点击组件(缩放 + 高亮,无涟漪) // 通用可点击组件
// ================================================== // ==================================================
class _ClickableTile extends StatefulWidget { class _ClickableTile extends StatefulWidget {
final Widget child; final Widget child;
@@ -61,7 +62,6 @@ class _ClickableTileState extends State<_ClickableTile>
with SingleTickerProviderStateMixin { with SingleTickerProviderStateMixin {
late final AnimationController _controller; late final AnimationController _controller;
late final Animation<double> _scale; late final Animation<double> _scale;
late final Animation<double> _opacity;
static const Duration _duration = Duration(milliseconds: 120); static const Duration _duration = Duration(milliseconds: 120);
@@ -72,9 +72,6 @@ class _ClickableTileState extends State<_ClickableTile>
_scale = Tween<double>(begin: 1.0, end: 0.95).animate( _scale = Tween<double>(begin: 1.0, end: 0.95).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeOut), CurvedAnimation(parent: _controller, curve: Curves.easeOut),
); );
_opacity = Tween<double>(begin: 0.0, end: 0.08).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeOut),
);
} }
@override @override
@@ -108,14 +105,7 @@ class _ClickableTileState extends State<_ClickableTile>
builder: (context, child) { builder: (context, child) {
return Transform.scale( return Transform.scale(
scale: _scale.value, scale: _scale.value,
child: Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(_opacity.value),
borderRadius: BorderRadius.circular(8),
),
padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 4),
child: child, child: child,
),
); );
}, },
child: widget.child, child: widget.child,
@@ -125,6 +115,31 @@ class _ClickableTileState extends State<_ClickableTile>
} }
} }
// ==================================================
// Sticky Header 委托
// ==================================================
class _StickyHeaderDelegate extends SliverPersistentHeaderDelegate {
final Widget child;
_StickyHeaderDelegate({required this.child});
@override
double get minExtent => 48;
@override
double get maxExtent => 48;
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return child;
}
@override
bool shouldRebuild(_StickyHeaderDelegate oldDelegate) {
return child != oldDelegate.child;
}
}
// ================================================== // ==================================================
// 主页 // 主页
// ================================================== // ==================================================
@@ -139,22 +154,96 @@ class _HomePageState extends State<HomePage> {
List<SongItem> _favorites = []; List<SongItem> _favorites = [];
bool _isLoading = true; bool _isLoading = true;
// ========== 滚动控制 ==========
late final ScrollController _scrollController;
final GlobalKey _mediaLibraryKey = GlobalKey();
double _mediaLibraryHeight = 0.0;
// 高度测量重试控制
int _heightMeasureRetryCount = 0;
static const int _maxHeightMeasureRetries = 10;
// ========== 计算属性 ==========
double get _progress {
if (_mediaLibraryHeight <= 0) return 0.0;
final offset =
_scrollController.hasClients ? _scrollController.offset : 0.0;
return (offset / _mediaLibraryHeight).clamp(0.0, 1.0);
}
// 媒体库透明度(快速淡出)
double get _mediaOpacity {
final p = _progress;
// 0% ~ 30%: 1.0 → 0.05
// 30% ~ 100%: 0.05 → 0
if (p <= 0.3) {
return 1.0 - (p / 0.3) * 0.95;
} else {
return 0.05 * (1 - (p - 0.3) / 0.7);
}
}
// 列表展开程度
double get _listReveal {
if (_progress <= 0.7) return 0.0;
return (_progress - 0.7) / 0.3;
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_scrollController = ScrollController()..addListener(_onScroll);
_initWebDAV(); _initWebDAV();
WidgetsBinding.instance.addPostFrameCallback((_) {
_measureMediaLibraryHeight();
});
} }
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
// ========== 高度测量(带重试限制) ==========
void _measureMediaLibraryHeight() {
final renderBox =
_mediaLibraryKey.currentContext?.findRenderObject() as RenderBox?;
if (renderBox != null) {
final height = renderBox.size.height;
if (height > 0 && height != _mediaLibraryHeight) {
setState(() {
_mediaLibraryHeight = height;
_heightMeasureRetryCount = 0;
});
print('✅ 媒体库高度测量成功: $height');
}
} else {
_heightMeasureRetryCount++;
if (_heightMeasureRetryCount < _maxHeightMeasureRetries) {
Future.delayed(
const Duration(milliseconds: 200), _measureMediaLibraryHeight);
} else {
print('⚠️ 媒体库高度测量失败,使用默认值 280px');
setState(() {
_mediaLibraryHeight = 280.0;
});
}
}
}
// ========== 滚动监听 ==========
void _onScroll() {
if (mounted) setState(() {});
}
// ========== 初始化 WebDAV ==========
Future<void> _initWebDAV() async { Future<void> _initWebDAV() async {
setState(() => _isLoading = true); setState(() => _isLoading = true);
try { try {
final hasCred = await WebDAVService.instance.loadCredentials(); await WebDAVService.instance.loadCredentials();
if (hasCred) {
// ✅ 不再自动加载音乐到收藏
_favorites = []; _favorites = [];
} else {
_favorites = [];
}
} catch (e) { } catch (e) {
_favorites = []; _favorites = [];
} finally { } finally {
@@ -162,35 +251,7 @@ class _HomePageState extends State<HomePage> {
} }
} }
Future<void> _loadMusicList() async { // ========== 播放 ==========
try {
final files = await WebDAVService.instance.getMusicFiles();
setState(() {
_favorites = files.map((file) {
return SongItem(
path: file.path,
fileName: file.name,
title: file.name.replaceAll(RegExp(r'\.[^.]*$'), ''),
artist: null,
sourceTag: 'webdav',
metadataState: 'unknown',
);
}).toList();
});
} catch (e) {
setState(() => _favorites = []);
}
}
Future<void> _refreshFromWebDAV() async {
final hasCred = await WebDAVService.instance.loadCredentials();
if (hasCred) {
await _loadMusicList();
} else {
setState(() => _favorites = []);
}
}
void _playSong(SongItem song) async { void _playSong(SongItem song) async {
try { try {
final url = WebDAVService.instance.getFileUrl(song.path); final url = WebDAVService.instance.getFileUrl(song.path);
@@ -213,9 +274,19 @@ class _HomePageState extends State<HomePage> {
} }
} }
// ========== 重置磁吸状态 ==========
void _resetSnapState() {
if (_scrollController.hasClients) {
_scrollController.jumpTo(0.0);
}
setState(() {});
}
// ================================================================
// Build
// ================================================================
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// 直接从 WebDAVService 读取实时状态
final isConnected = WebDAVService.instance.isConnected; final isConnected = WebDAVService.instance.isConnected;
final username = WebDAVService.instance.username ?? '点击连接'; final username = WebDAVService.instance.username ?? '点击连接';
final audioService = context.watch<AudioService>(); final audioService = context.watch<AudioService>();
@@ -223,16 +294,13 @@ class _HomePageState extends State<HomePage> {
return Scaffold( return Scaffold(
backgroundColor: const Color(0xFF0E1211), backgroundColor: const Color(0xFF0E1211),
body: Stack( body: Column(
children: [ children: [
CustomScrollView( // ---- 固定标题 "清听" ----
slivers: [ SafeArea(
// ---- 顶部标题 ---- bottom: false,
SliverToBoxAdapter(
child: SafeArea(
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
horizontal: 20, vertical: 12),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
@@ -252,11 +320,24 @@ class _HomePageState extends State<HomePage> {
), ),
), ),
), ),
),
// ---- 滚动区域 ----
Expanded(
child: CustomScrollView(
controller: _scrollController,
physics: _mediaLibraryHeight > 0
? MagneticScrollPhysics(
snapPoint: _mediaLibraryHeight,
magneticZoneStart: 0.20,
)
: const ClampingScrollPhysics(),
slivers: [
// ---- 媒体库 ---- // ---- 媒体库 ----
SliverToBoxAdapter( SliverToBoxAdapter(
child: Padding( child: Opacity(
opacity: _mediaOpacity,
child: Container(
key: _mediaLibraryKey,
padding: const EdgeInsets.symmetric(horizontal: 20), padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
@@ -270,32 +351,29 @@ class _HomePageState extends State<HomePage> {
), ),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// ---- WebDAV 入口 ----
_ClickableTile( _ClickableTile(
onTap: () async { onTap: () async {
if (WebDAVService.instance.isConnected) { if (WebDAVService.instance.isConnected) {
// 已连接 → 直接进入文件列表
await Navigator.push( await Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (_) => const WebDAVFileListPage(), builder: (_) => const WebDAVFileListPage(),
), ),
); );
// 返回后刷新界面(可能状态变化) _resetSnapState();
setState(() {}); setState(() {});
} else { } else {
// 未连接 → 进入设置页
final result = await Navigator.push( final result = await Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (_) => const WebDAVSetupPage(), builder: (_) => const WebDAVSetupPage(),
), ),
); );
// 从设置页返回后刷新
setState(() {}); setState(() {});
if (result == true) { if (result == true) {
await _refreshFromWebDAV(); await WebDAVService.instance
.loadCredentials();
setState(() {});
} }
} }
}, },
@@ -313,7 +391,8 @@ class _HomePageState extends State<HomePage> {
const SizedBox(width: 16), const SizedBox(width: 16),
Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment:
CrossAxisAlignment.start,
children: [ children: [
Row( Row(
children: [ children: [
@@ -355,18 +434,17 @@ class _HomePageState extends State<HomePage> {
), ),
), ),
const SizedBox(height: 24), const SizedBox(height: 24),
// ---- 三个功能入口 ----
Row( Row(
children: [ children: [
Expanded( Expanded(
child: _ClickableTile( child: _ClickableTile(
onTap: () {}, onTap: () {},
child: Padding( child: Padding(
padding: padding: const EdgeInsets.symmetric(
const EdgeInsets.symmetric(vertical: 10), vertical: 10),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment:
MainAxisAlignment.center,
children: [ children: [
Icon(Icons.music_note, Icon(Icons.music_note,
size: 24, size: 24,
@@ -390,10 +468,11 @@ class _HomePageState extends State<HomePage> {
child: _ClickableTile( child: _ClickableTile(
onTap: () {}, onTap: () {},
child: Padding( child: Padding(
padding: padding: const EdgeInsets.symmetric(
const EdgeInsets.symmetric(vertical: 10), vertical: 10),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment:
MainAxisAlignment.center,
children: [ children: [
Icon(Icons.history, Icon(Icons.history,
size: 24, size: 24,
@@ -417,10 +496,11 @@ class _HomePageState extends State<HomePage> {
child: _ClickableTile( child: _ClickableTile(
onTap: () {}, onTap: () {},
child: Padding( child: Padding(
padding: padding: const EdgeInsets.symmetric(
const EdgeInsets.symmetric(vertical: 10), vertical: 10),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment:
MainAxisAlignment.center,
children: [ children: [
Icon(Icons.playlist_play, Icon(Icons.playlist_play,
size: 24, size: 24,
@@ -446,13 +526,12 @@ class _HomePageState extends State<HomePage> {
), ),
), ),
), ),
),
// 在 home_page.dart 中,修改 SliverPersistentHeader 的 delegate // ---- "我的收藏" Sticky Header ----
SliverPersistentHeader( SliverPersistentHeader(
pinned: true, pinned: true,
delegate: _StickyHeaderDelegate( delegate: _StickyHeaderDelegate(
child: SafeArea(
bottom: false,
child: Container( child: Container(
height: 48, height: 48,
color: const Color(0xFF0E1211), color: const Color(0xFF0E1211),
@@ -475,7 +554,6 @@ class _HomePageState extends State<HomePage> {
), ),
), ),
), ),
),
// ---- 收藏列表 ---- // ---- 收藏列表 ----
SliverPadding( SliverPadding(
@@ -494,20 +572,21 @@ class _HomePageState extends State<HomePage> {
) )
: _favorites.isEmpty : _favorites.isEmpty
? SliverFillRemaining( ? SliverFillRemaining(
child: AnimatedOpacity(
opacity: 1.0 - _listReveal * 0.3,
duration: const Duration(milliseconds: 100),
child: Center( child: Center(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon( Icon(
Icons.music_note, Icons.favorite_border,
size: 48, size: 48,
color: Colors.grey[600], color: Colors.grey[600],
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
isConnected '还没有收藏歌曲\n在音乐库中点击 ♡ 添加',
? '还没有收藏歌曲\n去媒体库发现音乐'
: '请先连接 WebDAV',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
@@ -518,14 +597,22 @@ class _HomePageState extends State<HomePage> {
], ],
), ),
), ),
),
) )
: SliverList( : SliverList(
delegate: SliverChildBuilderDelegate( delegate: SliverChildBuilderDelegate(
(context, index) { (context, index) {
final song = _favorites[index]; final song = _favorites[index];
return Padding( final itemProgress =
padding: (_listReveal * 2 - index / 5)
const EdgeInsets.symmetric(vertical: 6), .clamp(0.0, 1.0);
return AnimatedOpacity(
opacity: itemProgress,
duration: const Duration(milliseconds: 150),
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 6),
child: ListTile( child: ListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
leading: const Icon( leading: const Icon(
@@ -552,8 +639,21 @@ class _HomePageState extends State<HomePage> {
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
trailing: IconButton(
icon: const Icon(
Icons.favorite,
color: Color(0xFFB8D4D0),
size: 20,
),
onPressed: () {
setState(() {
_favorites.removeAt(index);
});
},
),
onTap: () => _playSong(song), onTap: () => _playSong(song),
), ),
),
); );
}, },
childCount: _favorites.length, childCount: _favorites.length,
@@ -562,42 +662,12 @@ class _HomePageState extends State<HomePage> {
), ),
], ],
), ),
),
// ---- 底部 MiniPlayer ---- // ---- 底部 MiniPlayer ----
if (showMiniBar) if (showMiniBar) const MiniPlayerBar(),
const Positioned(
left: 0,
right: 0,
bottom: 0,
child: MiniPlayerBar(),
),
], ],
), ),
); );
} }
} }
// ==================================================
// Sticky Header 委托
// ==================================================
class _StickyHeaderDelegate extends SliverPersistentHeaderDelegate {
final Widget child;
_StickyHeaderDelegate({required this.child});
@override
double get minExtent => 48;
@override
double get maxExtent => 48;
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return child;
}
@override
bool shouldRebuild(_StickyHeaderDelegate oldDelegate) {
return child != oldDelegate.child;
}
}
+40 -59
View File
@@ -1,9 +1,4 @@
// ============================================================ // lib/pages/webdav_file_list_page.dart
// 文件名: webdav_file_list_page.dart
// 功能: WebDAV 文件浏览页面,支持文件夹导航和音乐播放
// 调用方式: Navigator.push(context, MaterialPageRoute(builder: (_) => WebDAVFileListPage()))
// ============================================================
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../services/webdav_service.dart'; import '../services/webdav_service.dart';
@@ -11,7 +6,6 @@ import '../services/playback_service.dart';
import '../services/audio_service.dart'; import '../services/audio_service.dart';
class WebDAVFileListPage extends StatefulWidget { class WebDAVFileListPage extends StatefulWidget {
/// 当前浏览路径,默认为根目录 '/'
final String currentPath; final String currentPath;
const WebDAVFileListPage({super.key, this.currentPath = '/'}); const WebDAVFileListPage({super.key, this.currentPath = '/'});
@@ -26,6 +20,15 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
String _errorMessage = ''; String _errorMessage = '';
String _currentPath = '/'; String _currentPath = '/';
// 安全解码
String _safeDecode(String input) {
try {
return Uri.decodeComponent(input);
} catch (_) {
return input; // 解码失败时返回原始字符串
}
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -33,9 +36,6 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
_loadDirectory(); _loadDirectory();
} }
// -------------------------------------------------------------
// 加载当前目录内容
// -------------------------------------------------------------
Future<void> _loadDirectory() async { Future<void> _loadDirectory() async {
setState(() { setState(() {
_isLoading = true; _isLoading = true;
@@ -57,9 +57,6 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
} }
} }
// -------------------------------------------------------------
// 进入子目录
// -------------------------------------------------------------
void _enterDirectory(WebDAVItem dir) { void _enterDirectory(WebDAVItem dir) {
Navigator.push( Navigator.push(
context, context,
@@ -69,9 +66,6 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
); );
} }
// -------------------------------------------------------------
// 播放音乐文件
// -------------------------------------------------------------
void _playSong(WebDAVItem file) async { void _playSong(WebDAVItem file) async {
try { try {
final url = WebDAVService.instance.getFileUrl(file.path); final url = WebDAVService.instance.getFileUrl(file.path);
@@ -79,13 +73,11 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
final song = Song( final song = Song(
id: file.path, id: file.path,
title: file.name.replaceAll(RegExp(r'\.[^.]*$'), ''), title: _safeDecode(file.name).replaceAll(RegExp(r'\.[^.]*$'), ''),
artist: '未知艺术家', artist: '未知艺术家',
url: url, url: url,
); );
context.read<AudioService>().playSong(song); context.read<AudioService>().playSong(song);
// ✅ 移除 SnackBar,直接显示 MiniPlayer
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -98,12 +90,13 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
} }
} }
// -------------------------------------------------------------
// 构建面包屑路径显示(只显示最后两级,避免过长)
// -------------------------------------------------------------
String _getDisplayPath() { String _getDisplayPath() {
if (_currentPath == '/') return '根目录'; if (_currentPath == '/' || _currentPath.isEmpty) return '根目录';
final parts = _currentPath.split('/').where((s) => s.isNotEmpty).toList();
final decoded = _safeDecode(_currentPath);
final parts = decoded.split('/').where((s) => s.isNotEmpty).toList();
if (parts.isEmpty) return '根目录';
if (parts.length <= 2) return parts.join(' / '); if (parts.length <= 2) return parts.join(' / ');
return '... / ${parts.sublist(parts.length - 2).join(' / ')}'; return '... / ${parts.sublist(parts.length - 2).join(' / ')}';
} }
@@ -132,28 +125,19 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
), ),
], ],
), ),
body: _buildBody(), body: _isLoading
); ? const Center(
}
// -------------------------------------------------------------
// 构建主体内容
// -------------------------------------------------------------
Widget _buildBody() {
if (_isLoading) {
return const Center(
child: CircularProgressIndicator( child: CircularProgressIndicator(
color: Color(0xFFB8D4D0), color: Color(0xFFB8D4D0),
), ),
); )
} : _errorMessage.isNotEmpty
? Center(
if (_errorMessage.isNotEmpty) {
return Center(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon(Icons.error_outline, size: 48, color: Colors.grey[600]), Icon(Icons.error_outline,
size: 48, color: Colors.grey[600]),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
_errorMessage, _errorMessage,
@@ -171,15 +155,14 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
), ),
], ],
), ),
); )
} : _items.isEmpty
? Center(
if (_items.isEmpty) {
return Center(
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon(Icons.folder_open, size: 48, color: Colors.grey[600]), Icon(Icons.folder_open,
size: 48, color: Colors.grey[600]),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
'此目录为空', '此目录为空',
@@ -188,29 +171,28 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
'支持格式: MP3, FLAC, M4A, APE, WAV, OPUS', '支持格式: MP3, FLAC, M4A, APE, WAV, OPUS',
style: TextStyle(color: Colors.grey[600], fontSize: 12), style: TextStyle(
color: Colors.grey[600], fontSize: 12),
), ),
], ],
), ),
); )
} : ListView.builder(
padding: const EdgeInsets.symmetric(
return ListView.builder( horizontal: 16, vertical: 8),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
itemCount: _items.length, itemCount: _items.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
final item = _items[index]; final item = _items[index];
return _buildListItem(item); return _buildListItem(item);
}, },
),
); );
} }
// -------------------------------------------------------------
// 构建单个列表项(区分目录和文件)
// -------------------------------------------------------------
Widget _buildListItem(WebDAVItem item) { Widget _buildListItem(WebDAVItem item) {
final displayName = _safeDecode(item.name);
if (item.isDirectory) { if (item.isDirectory) {
// ---------- 目录项 ----------
return ListTile( return ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), contentPadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
leading: const Icon( leading: const Icon(
@@ -219,7 +201,7 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
size: 32, size: 32,
), ),
title: Text( title: Text(
item.name, displayName,
style: const TextStyle( style: const TextStyle(
fontSize: 16, fontSize: 16,
fontWeight: FontWeight.w500, fontWeight: FontWeight.w500,
@@ -242,7 +224,6 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
onTap: () => _enterDirectory(item), onTap: () => _enterDirectory(item),
); );
} else { } else {
// ---------- 音乐文件项 ----------
final sizeStr = item.size != null final sizeStr = item.size != null
? '${(item.size! / 1024 / 1024).toStringAsFixed(1)} MB' ? '${(item.size! / 1024 / 1024).toStringAsFixed(1)} MB'
: ''; : '';
@@ -254,7 +235,7 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
size: 28, size: 28,
), ),
title: Text( title: Text(
item.name, displayName,
style: const TextStyle( style: const TextStyle(
fontSize: 16, fontSize: 16,
fontWeight: FontWeight.w400, fontWeight: FontWeight.w400,
+32 -55
View File
@@ -1,16 +1,9 @@
// ============================================================ // lib/services/webdav_service.dart
// 文件名: webdav_service.dart
// 功能: WebDAV 协议通信服务,支持文件夹浏览和音乐文件读取
// ============================================================
import 'dart:convert'; import 'dart:convert';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:xml/xml.dart'; import 'package:xml/xml.dart';
// -----------------------------------------------------------------
// WebDAV 服务单例
// -----------------------------------------------------------------
class WebDAVService { class WebDAVService {
static const String _keyBaseUrl = 'webdav_base_url'; static const String _keyBaseUrl = 'webdav_base_url';
static const String _keyUsername = 'webdav_username'; static const String _keyUsername = 'webdav_username';
@@ -25,16 +18,11 @@ class WebDAVService {
String? _baseUrl; String? _baseUrl;
String? _username; String? _username;
// -------------------------------------------------------------
// 公开 Getter
// -------------------------------------------------------------
bool get isConnected => _dio != null; bool get isConnected => _dio != null;
String? get baseUrl => _baseUrl; String? get baseUrl => _baseUrl;
String? get username => _username; String? get username => _username;
// ------------------------------------------------------------- // 保存凭据
// 凭据管理
// -------------------------------------------------------------
Future<void> saveCredentials( Future<void> saveCredentials(
String baseUrl, String username, String password) async { String baseUrl, String username, String password) async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
@@ -53,6 +41,7 @@ class WebDAVService {
)); ));
} }
// 加载已保存的凭据
Future<bool> loadCredentials() async { Future<bool> loadCredentials() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final baseUrl = prefs.getString(_keyBaseUrl); final baseUrl = prefs.getString(_keyBaseUrl);
@@ -74,6 +63,7 @@ class WebDAVService {
return false; return false;
} }
// 清除凭据
Future<void> clearCredentials() async { Future<void> clearCredentials() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.remove(_keyBaseUrl); await prefs.remove(_keyBaseUrl);
@@ -84,15 +74,22 @@ class WebDAVService {
_username = null; _username = null;
} }
// ------------------------------------------------------------- // 获取音乐文件列表(PROPFIND
// 核心:列出目录内容(文件夹 + 音乐文件)
// 这是浏览模式的核心方法,支持进入子目录
// -------------------------------------------------------------
Future<List<WebDAVItem>> listDirectory({String path = '/'}) async { Future<List<WebDAVItem>> listDirectory({String path = '/'}) async {
if (_dio == null) throw Exception('WebDAV 未连接'); if (_dio == null) throw Exception('WebDAV 未连接');
final requestPath = path.startsWith('/') ? path : '/$path'; final requestPath = path.startsWith('/') ? path : '/$path';
// 路径规范化:去掉首尾斜杠,用于比较
String _normalize(String p) {
var s = p;
if (s.startsWith('/')) s = s.substring(1);
if (s.endsWith('/')) s = s.substring(0, s.length - 1);
return s;
}
final normalizedRequest = _normalize(requestPath);
final body = ''' final body = '''
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<propfind xmlns="DAV:"> <propfind xmlns="DAV:">
@@ -124,14 +121,13 @@ class WebDAVService {
final items = <WebDAVItem>[]; final items = <WebDAVItem>[];
final musicExtensions = ['.mp3', '.flac', '.m4a', '.ape', '.wav', '.opus']; final musicExtensions = ['.mp3', '.flac', '.m4a', '.ape', '.wav', '.opus'];
final responseNodes = xml.findAllElements('D:response'); for (final responseNode in xml.findAllElements('D:response')) {
for (final responseNode in responseNodes) {
final hrefNode = responseNode.findElements('D:href').firstOrNull; final hrefNode = responseNode.findElements('D:href').firstOrNull;
if (hrefNode == null) continue; if (hrefNode == null) continue;
String fullPath = Uri.decodeComponent(hrefNode.text.trim()); String fullPath = Uri.decodeComponent(hrefNode.text.trim());
// 去掉 baseUrl 前缀 // 去掉 baseUrl 前缀,得到相对路径
String relativePath = fullPath; String relativePath = fullPath;
if (_baseUrl != null) { if (_baseUrl != null) {
try { try {
@@ -149,10 +145,10 @@ class WebDAVService {
} }
} }
// 跳过根目录自身 // 使用规范化路径比较,跳过当前目录自身
if (relativePath.isEmpty || final normalizedRelative = _normalize(relativePath);
relativePath == '/' || if (normalizedRelative.isEmpty ||
relativePath == requestPath) { normalizedRelative == normalizedRequest) {
continue; continue;
} }
@@ -160,7 +156,6 @@ class WebDAVService {
? relativePath.substring(0, relativePath.length - 1) ? relativePath.substring(0, relativePath.length - 1)
: relativePath; : relativePath;
// ✅ 解码文件名
String fileName = cleanPath.split('/').last; String fileName = cleanPath.split('/').last;
fileName = Uri.decodeComponent(fileName); fileName = Uri.decodeComponent(fileName);
if (fileName.isEmpty) continue; if (fileName.isEmpty) continue;
@@ -219,26 +214,28 @@ class WebDAVService {
)); ));
} }
// 排序 // 排序:目录在前,文件在后
items.sort((a, b) { items.sort((a, b) {
if (a.isDirectory && !b.isDirectory) return -1; if (a.isDirectory && !b.isDirectory) return -1;
if (!a.isDirectory && b.isDirectory) return 1; if (!a.isDirectory && b.isDirectory) return 1;
return a.name.toLowerCase().compareTo(b.name.toLowerCase()); return a.name.toLowerCase().compareTo(b.name.toLowerCase());
}); });
// 只保留一条日志,避免刷屏
print('WebDAV listDirectory: 找到 ${items.length} 项,路径: $requestPath');
return items; return items;
} }
// ------------------------------------------------------------- // 获取文件完整 URL
// 兼容旧接口:获取所有音乐文件(递归扫描) String getFileUrl(String path) {
// 用于主页的"我的收藏"列表(后续可改为读取用户收藏) if (_baseUrl == null) throw Exception('WebDAV 未配置');
// ------------------------------------------------------------- final base = _baseUrl!.endsWith('/') ? _baseUrl! : '$_baseUrl/';
final cleanPath = path.startsWith('/') ? path.substring(1) : path;
return '$base$cleanPath';
}
// 递归获取所有音乐文件(用于收藏列表)
Future<List<WebDAVFileItem>> getMusicFiles({String path = '/'}) async { Future<List<WebDAVFileItem>> getMusicFiles({String path = '/'}) async {
if (_dio == null) throw Exception('WebDAV 未连接'); if (_dio == null) throw Exception('WebDAV 未连接');
// 递归获取所有文件(先获取当前目录,再递归子目录)
final allItems = await _listAllRecursive(path); final allItems = await _listAllRecursive(path);
final musicExtensions = ['.mp3', '.flac', '.m4a', '.ape', '.wav', '.opus']; final musicExtensions = ['.mp3', '.flac', '.m4a', '.ape', '.wav', '.opus'];
@@ -255,7 +252,6 @@ class WebDAVService {
.toList(); .toList();
} }
// 递归获取所有目录和文件(内部使用)
Future<List<WebDAVItem>> _listAllRecursive(String path) async { Future<List<WebDAVItem>> _listAllRecursive(String path) async {
final items = await listDirectory(path: path); final items = await listDirectory(path: path);
final result = <WebDAVItem>[]; final result = <WebDAVItem>[];
@@ -263,32 +259,16 @@ class WebDAVService {
for (final item in items) { for (final item in items) {
result.add(item); result.add(item);
if (item.isDirectory) { if (item.isDirectory) {
// 递归获取子目录内容
try { try {
final subItems = await _listAllRecursive(item.path); final subItems = await _listAllRecursive(item.path);
result.addAll(subItems); result.addAll(subItems);
} catch (_) { } catch (_) {}
// 忽略无法读取的子目录
}
} }
} }
return result; return result;
} }
// -------------------------------------------------------------
// 获取文件的完整下载 URL
// -------------------------------------------------------------
String getFileUrl(String path) {
if (_baseUrl == null) throw Exception('WebDAV 未配置');
final base = _baseUrl!.endsWith('/') ? _baseUrl! : '$_baseUrl/';
final cleanPath = path.startsWith('/') ? path.substring(1) : path;
return '$base$cleanPath';
}
} }
// -----------------------------------------------------------------
// 数据模型:WebDAV 目录项(用于浏览模式)
// -----------------------------------------------------------------
class WebDAVItem { class WebDAVItem {
final String path; final String path;
final String name; final String name;
@@ -305,9 +285,6 @@ class WebDAVItem {
}); });
} }
// -----------------------------------------------------------------
// 数据模型:WebDAV 文件项(用于播放列表)
// -----------------------------------------------------------------
class WebDAVFileItem { class WebDAVFileItem {
final String path; final String path;
final String name; final String name;
+150
View File
@@ -0,0 +1,150 @@
import 'package:flutter/material.dart';
/// 磁吸进度状态
class MagneticSnapState {
/// 吸附进度 0.0 ~ 1.0
final double progress;
/// 媒体库透明度
double get mediaOpacity {
// 0% ~ 70%: 1.0 → 0.45
// 70% ~ 100%: 0.45 → 0
if (progress <= 0.7) {
return 1.0 - (progress / 0.7) * 0.55;
} else {
final t = (progress - 0.7) / 0.3;
return 0.45 * (1 - t);
}
}
/// 收藏标题位移(从 +12px → 0)
double get favoriteTranslateY {
return (1 - progress) * 12;
}
/// 收藏列表展开程度 0.0 ~ 1.0
double get listReveal {
if (progress <= 0.7) return 0.0;
return (progress - 0.7) / 0.3;
}
/// 是否完全吸附
bool get isSnapped => progress >= 1.0;
/// 是否在磁吸区(进度 > 70%)
bool get isInMagneticZone => progress > 0.7;
const MagneticSnapState(this.progress);
factory MagneticSnapState.initial() => const MagneticSnapState(0.0);
MagneticSnapState copyWith({double? progress}) {
return MagneticSnapState(progress ?? this.progress);
}
}
/// 磁吸控制器
class MagneticScrollController extends ChangeNotifier {
/// 吸附进度
double _progress = 0.0;
double get progress => _progress;
/// 是否已吸附
bool _isSnapped = false;
bool get isSnapped => _isSnapped;
/// 动画控制器(用于吸附动画)
AnimationController? _animationController;
TickerProvider? _tickerProvider;
/// 状态
MagneticSnapState get state => MagneticSnapState(_progress);
void init(TickerProvider vsync) {
_animationController = AnimationController(
vsync: vsync,
duration: const Duration(milliseconds: 300),
);
}
@override
void dispose() {
_animationController?.dispose();
super.dispose();
}
/// 更新滚动进度(在滚动时调用)
void updateProgress(double newProgress) {
if (_isSnapped) return;
_progress = newProgress.clamp(0.0, 1.0);
notifyListeners();
}
/// 处理松手事件
void onDragEnd(double velocity) {
if (_isSnapped) return;
final threshold = 0.45; // 45% 触发吸附
final shouldSnap = _progress > threshold || velocity > 800;
if (shouldSnap) {
snapOpen();
} else {
snapBack();
}
}
/// 吸附展开
void snapOpen() {
if (_isSnapped) return;
_isSnapped = true;
_animationController?.reset();
_animationController
?.animateTo(
1.0,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOutBack,
)
.then((_) {
_progress = 1.0;
notifyListeners();
});
// 实时更新进度
_animationController?.addListener(() {
_progress = _animationController!.value;
notifyListeners();
});
}
/// 回弹
void snapBack() {
if (_isSnapped) return;
_animationController?.reset();
_animationController
?.animateTo(
0.0,
duration: const Duration(milliseconds: 250),
curve: Curves.easeOut,
)
.then((_) {
_progress = 0.0;
notifyListeners();
});
_animationController?.addListener(() {
_progress = _animationController!.value;
notifyListeners();
});
}
/// 重置状态(退出页面时)
void reset() {
_isSnapped = false;
_progress = 0.0;
_animationController?.reset();
notifyListeners();
}
}
+74
View File
@@ -0,0 +1,74 @@
// lib/widgets/magnetic_scroll_physics.dart
import 'package:flutter/material.dart';
class MagneticScrollPhysics extends ClampingScrollPhysics {
final double snapPoint;
final double magneticZoneStart;
const MagneticScrollPhysics({
required this.snapPoint,
this.magneticZoneStart = 0.20,
super.parent,
});
@override
MagneticScrollPhysics applyTo(ScrollPhysics? ancestor) {
return MagneticScrollPhysics(
snapPoint: snapPoint,
magneticZoneStart: magneticZoneStart,
parent: buildParent(ancestor),
);
}
@override
Simulation? createBallisticSimulation(
ScrollMetrics position,
double velocity,
) {
final offset = position.pixels;
if (offset <= 0 || offset >= snapPoint) {
return super.createBallisticSimulation(position, velocity);
}
final shouldSnap = _shouldSnap(offset, velocity);
final target = shouldSnap ? snapPoint : 0.0;
if ((offset - target).abs() < 1.0) {
return null;
}
return ScrollSpringSimulation(
SpringDescription(
mass: 1.0,
stiffness: 320.0,
damping: 26.0,
),
offset,
target,
velocity,
tolerance: const Tolerance(
velocity: 0.01,
distance: 0.5,
),
);
}
bool _shouldSnap(double offset, double velocity) {
final zoneStart = snapPoint * magneticZoneStart;
// 向上滑 → 吸附展开
if (velocity > 20) {
return true;
}
// 向下滑 → 回去
if (velocity < -20) {
return false;
}
// 松手速度很小,用当前位置决定
return offset >= zoneStart;
}
}