// 首页:搜索 + 列表 + 导入同步 + 新增入口。 import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import '../../application/providers.dart'; import '../../domain/bookmark.dart'; import '../widgets/bookmark_tile.dart'; import '../widgets/empty_state.dart'; class HomePage extends ConsumerWidget { const HomePage({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final AsyncValue> filtered = ref.watch(filteredBookmarksProvider); final SyncState sync = ref.watch(syncProvider); return Scaffold( appBar: AppBar( title: const Text('书签'), actions: [ IconButton( key: const Key('sync'), tooltip: '从远程导入', onPressed: sync.running ? null : () => ref.read(syncProvider.notifier).run(), icon: sync.running ? const SizedBox( width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, key: Key('sync-loading')), ) : const Icon(Icons.cloud_download_outlined), ), ], ), body: Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(12, 12, 12, 4), child: TextField( key: const Key('search'), decoration: const InputDecoration( hintText: '搜索标题 / 备注 / 链接', prefixIcon: Icon(Icons.search), border: OutlineInputBorder(), isDense: true, ), onChanged: (String value) => ref.read(searchQueryProvider.notifier).set(value), ), ), if (sync.error != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Text( '同步失败:${sync.error}', key: const Key('sync-error'), style: TextStyle(color: Theme.of(context).colorScheme.error), ), ), if (sync.lastImported != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Text('本次导入 ${sync.lastImported} 条', key: const Key('sync-result')), ), Expanded( child: filtered.when( loading: () => const Center(child: CircularProgressIndicator(key: Key('list-loading'))), error: (Object e, StackTrace _) => Center(child: Text('读取失败:$e')), data: (List items) { if (items.isEmpty) { final bool searching = ref.watch(searchQueryProvider).trim().isNotEmpty; return EmptyState( // 空列表要区分"真的没有"和"搜不到",否则用户会以为数据丢了。 message: searching ? '没有匹配「${ref.watch(searchQueryProvider)}」的书签' : '还没有书签', hint: searching ? '换个关键字试试' : '点右下角 + 新建,或用右上角从远程导入', ); } // ListView.builder:惰性构建,列表几千条也不卡(ch17 详述)。 return ListView.builder( key: const Key('bookmark-list'), padding: const EdgeInsets.symmetric(vertical: 8), itemCount: items.length, itemBuilder: (BuildContext context, int index) { final Bookmark bookmark = items[index]; return BookmarkTile( key: ValueKey(bookmark.id), bookmark: bookmark, onTap: () => context.push('/bookmark/${bookmark.id}'), onToggleFavorite: () => ref.read(bookmarkActionsProvider).toggleFavorite(bookmark), ); }, ); }, ), ), ], ), floatingActionButton: FloatingActionButton( key: const Key('add'), onPressed: () => context.push('/new'), tooltip: '新建书签', child: const Icon(Icons.add), ), ); } }