结构重构

This commit is contained in:
DelLevin-Home
2026-03-12 14:33:28 +08:00
parent f63b5b1843
commit 0f221456cb
39 changed files with 106 additions and 105 deletions

View File

@@ -0,0 +1,737 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:cross_file/cross_file.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../utils/toast_util.dart';
import 'book_reviews_page.dart';
import 'book_excerpts_page.dart';
/// 书籍详情页 - 极简主义设计
class BookDetailPage extends StatefulWidget {
final Book book;
const BookDetailPage({super.key, required this.book});
@override
State<BookDetailPage> createState() => _BookDetailPageState();
}
class _BookDetailPageState extends State<BookDetailPage> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
// 页面获得焦点时刷新数据
_refreshBookData();
}
void _refreshBookData() {
final provider = context.read<AppProvider>();
// 强制刷新当前书籍数据
provider.loadBooks();
}
@override
Widget build(BuildContext context) {
// 从 Provider 获取最新的 book 数据,实现动态刷新
final book = context.watch<AppProvider>().books
.where((b) => b.id == widget.book.id)
.firstOrNull ?? widget.book;
return Scaffold(
backgroundColor: Colors.white,
body: CustomScrollView(
slivers: [
// 顶部封面区域
_buildSliverAppBar(book),
// 内容区域
SliverToBoxAdapter(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 基本信息
_buildBasicInfo(book),
const Divider(height: 0.5, thickness: 0.5, color: Color(0xFFE5E5E5)),
// 作者信息
_buildAuthorsSection(book),
// 出版社
if (book.publisher != null && book.publisher!.isNotEmpty)
_buildPublisherSection(book),
// 类型
if (book.genres.isNotEmpty)
_buildGenresSection(book),
const Divider(height: 0.5, thickness: 0.5, color: Color(0xFFE5E5E5)),
// 简介
if (book.summary != null && book.summary!.isNotEmpty)
_buildSummarySection(book),
const Divider(height: 0.5, thickness: 0.5, color: Color(0xFFE5E5E5)),
// 书评和摘抄入口
_buildExtraSections(book),
const SizedBox(height: 48),
],
),
),
],
),
// 底部操作栏
bottomNavigationBar: _buildBottomBar(),
);
}
/// 构建顶部 AppBar
Widget _buildSliverAppBar(Book book) {
final hasCover = book.coverPath != null && book.coverPath!.isNotEmpty;
return SliverAppBar(
expandedHeight: 320,
pinned: true,
backgroundColor: const Color(0xFFF5F5F5),
flexibleSpace: FlexibleSpaceBar(
background: _buildCoverSection(book),
),
actions: [
// 下载封面按钮(仅当有封面时显示)
if (hasCover)
Container(
margin: const EdgeInsets.all(8),
decoration: const BoxDecoration(
color: Colors.white,
),
child: IconButton(
icon: const Icon(Icons.download_outlined, color: Color(0xFF666666)),
onPressed: () => _downloadCover(book),
tooltip: '下载封面',
),
),
// 清空封面按钮(仅当有封面时显示)
if (hasCover)
Container(
margin: const EdgeInsets.all(8),
decoration: const BoxDecoration(
color: Colors.white,
),
child: IconButton(
icon: const Icon(Icons.hide_image_outlined, color: Color(0xFF666666)),
onPressed: () => _showClearCoverDialog(book),
tooltip: '清空封面',
),
),
// 编辑按钮
Container(
margin: const EdgeInsets.all(8),
decoration: const BoxDecoration(
color: Colors.white,
),
child: IconButton(
icon: const Icon(Icons.edit_outlined, color: Color(0xFF1A1A1A)),
onPressed: () => _navigateToEdit(context),
),
),
const SizedBox(width: 8),
],
);
}
/// 构建封面区域
Widget _buildCoverSection(Book book) {
return SizedBox.expand(
child: book.coverPath != null && book.coverPath!.isNotEmpty
? Image.file(
File(book.coverPath!),
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => _buildCoverPlaceholder(),
)
: _buildCoverPlaceholder(),
);
}
Widget _buildCoverPlaceholder() {
return const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.menu_book,
size: 64,
color: Color(0xFFCCCCCC),
),
SizedBox(height: 16),
Text(
'暂无封面',
style: TextStyle(
fontSize: 14,
color: Color(0xFF999999),
),
),
],
),
);
}
/// 构建基本信息
Widget _buildBasicInfo(Book book) {
return Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 书名
Text(
book.title,
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
color: Color(0xFF1A1A1A),
height: 1.3,
),
),
// 别名(显示在主名称下面,用 / 分隔)
if (book.alternateTitles.isNotEmpty) ...[
const SizedBox(height: 8),
Text(
book.alternateTitles.join(' / '),
style: const TextStyle(
fontSize: 14,
color: Color(0xFF999999),
height: 1.4,
),
),
],
const SizedBox(height: 16),
// 评分和状态
Row(
children: [
if (book.rating != null) ...[
const Icon(
Icons.star,
size: 20,
color: Color(0xFF1A1A1A),
),
const SizedBox(width: 4),
Text(
book.rating!.toStringAsFixed(1),
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Color(0xFF1A1A1A),
),
),
const SizedBox(width: 16),
],
_buildStatusTag(book),
],
),
const SizedBox(height: 8),
// 时间信息
Text(
'添加于 ${_formatDate(book.createdAt)}',
style: const TextStyle(
fontSize: 12,
color: Color(0xFF999999),
),
),
],
),
);
}
/// 构建状态标签
Widget _buildStatusTag(Book book) {
String label;
Color color;
switch (book.status) {
case 'read':
label = '已读';
color = const Color(0xFF1A1A1A);
break;
case 'reading':
label = '在读';
color = const Color(0xFF666666);
break;
case 'want_to_read':
label = '想读';
color = const Color(0xFF999999);
break;
default:
label = '未知';
color = const Color(0xFFCCCCCC);
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: color,
),
child: Text(
label,
style: const TextStyle(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
);
}
/// 构建作者区域
Widget _buildAuthorsSection(Book book) {
return Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'作者',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Color(0xFF999999),
letterSpacing: 1,
),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: book.authors.map((author) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Text(
author,
style: const TextStyle(
fontSize: 14,
color: Color(0xFF1A1A1A),
),
),
);
}).toList(),
),
],
),
);
}
/// 构建出版社区域
Widget _buildPublisherSection(Book book) {
return Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'出版社',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Color(0xFF999999),
letterSpacing: 1,
),
),
const SizedBox(height: 8),
Text(
book.publisher!,
style: const TextStyle(
fontSize: 15,
color: Color(0xFF1A1A1A),
),
),
],
),
);
}
/// 构建类型区域
Widget _buildGenresSection(Book book) {
return Padding(
padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'类型',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Color(0xFF999999),
letterSpacing: 1,
),
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: book.genres.map((genre) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Text(
genre,
style: const TextStyle(
fontSize: 13,
color: Color(0xFF666666),
),
),
);
}).toList(),
),
],
),
);
}
/// 构建简介区域
Widget _buildSummarySection(Book book) {
return Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'简介',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Color(0xFF999999),
letterSpacing: 1,
),
),
const SizedBox(height: 12),
Text(
book.summary!,
style: const TextStyle(
fontSize: 15,
color: Color(0xFF1A1A1A),
height: 1.6,
),
),
],
),
);
}
/// 构建额外功能区域(书评、摘抄)
Widget _buildExtraSections(Book book) {
return Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'更多',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Color(0xFF999999),
letterSpacing: 1,
),
),
const SizedBox(height: 16),
// 书评入口
GestureDetector(
onTap: () => _navigateToReviews(book),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Row(
children: [
const Icon(
Icons.rate_review_outlined,
size: 24,
color: Color(0xFF666666),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'书评',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
color: Color(0xFF1A1A1A),
),
),
const SizedBox(height: 4),
FutureBuilder<int>(
future: context.read<AppProvider>().getBookReviewCount(book.id),
builder: (context, snapshot) {
final count = snapshot.data ?? 0;
return Text(
count > 0 ? '$count 条书评' : '暂无书评',
style: const TextStyle(
fontSize: 13,
color: Color(0xFF999999),
),
);
},
),
],
),
),
const Icon(
Icons.chevron_right,
color: Color(0xFF999999),
),
],
),
),
),
const SizedBox(height: 12),
// 摘抄入口
GestureDetector(
onTap: () => _navigateToExcerpts(book),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Row(
children: [
const Icon(
Icons.format_quote_outlined,
size: 24,
color: Color(0xFF666666),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'摘抄',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
color: Color(0xFF1A1A1A),
),
),
const SizedBox(height: 4),
FutureBuilder<int>(
future: context.read<AppProvider>().getBookExcerptCount(book.id),
builder: (context, snapshot) {
final count = snapshot.data ?? 0;
return Text(
count > 0 ? '$count 条摘抄' : '暂无摘抄',
style: const TextStyle(
fontSize: 13,
color: Color(0xFF999999),
),
);
},
),
],
),
),
const Icon(
Icons.chevron_right,
color: Color(0xFF999999),
),
],
),
),
),
],
),
);
}
void _navigateToReviews(Book book) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookReviewsPage(book: book),
),
);
}
void _navigateToExcerpts(Book book) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookExcerptsPage(book: book),
),
);
}
/// 构建底部操作栏
Widget _buildBottomBar() {
return Container(
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: Color(0xFFE5E5E5), width: 0.5),
),
),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => _navigateToEdit(context),
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFF1A1A1A),
side: const BorderSide(color: Color(0xFF1A1A1A)),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: const Text('编辑'),
),
),
const SizedBox(width: 16),
Expanded(
child: OutlinedButton(
onPressed: () => _showDeleteDialog(context),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.red,
side: const BorderSide(color: Colors.red),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: const Text('删除'),
),
),
],
),
),
),
);
}
/// 格式化日期
String _formatDate(DateTime date) {
return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
}
/// 跳转到编辑页面
void _navigateToEdit(BuildContext context) {
Navigator.pushNamed(context, '/book-form', arguments: widget.book).then((_) {
context.read<AppProvider>().loadBooks();
});
}
/// 显示删除对话框
void _showDeleteDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text('确认删除'),
content: Text('确定要删除"${widget.book.title}"吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () async {
await context.read<AppProvider>().removeBook(widget.book.id);
if (!mounted) return;
Navigator.pop(context);
Navigator.pop(context);
ToastUtil.show(context, '已删除');
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
/// 显示清空封面对话框
void _showClearCoverDialog(Book book) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text('清空封面'),
content: const Text('确定要清空封面吗?清空后将使用默认占位图。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () async {
Navigator.pop(context);
final updatedBook = book.copyWith(
coverPath: null,
updatedAt: DateTime.now(),
);
await context.read<AppProvider>().updateBook(updatedBook);
if (mounted) {
ToastUtil.show(context, '封面已清空');
}
},
child: const Text('清空', style: TextStyle(color: Colors.red)),
),
],
),
);
}
/// 下载封面到本地
Future<void> _downloadCover(Book book) async {
if (book.coverPath == null || book.coverPath!.isEmpty) {
ToastUtil.show(context, '没有可下载的封面');
return;
}
try {
final sourceFile = File(book.coverPath!);
if (!await sourceFile.exists()) {
ToastUtil.show(context, '封面文件不存在');
return;
}
// 生成文件名书籍名称_时间戳_封面.jpg
final timestamp = DateTime.now().millisecondsSinceEpoch;
final fileName = '${book.title}_${timestamp}_封面.jpg';
// 获取临时目录路径
final tempDir = await Directory.systemTemp.createTemp();
final tempFile = File('${tempDir.path}/$fileName');
await sourceFile.copy(tempFile.path);
// 使用分享功能让用户选择保存位置
await Share.shareXFiles(
[XFile(tempFile.path)],
subject: '${book.title} 封面',
text: '下载自 MookNote',
);
} catch (e) {
ToastUtil.show(context, '下载失败: $e');
}
}
}

View File

@@ -0,0 +1,188 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../utils/toast_util.dart';
import 'package:uuid/uuid.dart';
/// 摘抄表单页面 - 新增/编辑摘抄
class BookExcerptFormPage extends StatefulWidget {
final String bookId;
final BookExcerpt? excerpt;
const BookExcerptFormPage({
super.key,
required this.bookId,
this.excerpt,
});
@override
State<BookExcerptFormPage> createState() => _BookExcerptFormPageState();
}
class _BookExcerptFormPageState extends State<BookExcerptFormPage> {
final _formKey = GlobalKey<FormState>();
final _chapterController = TextEditingController();
final _contentController = TextEditingController();
final _commentController = TextEditingController();
bool _isLoading = false;
bool get _isEditing => widget.excerpt != null;
@override
void initState() {
super.initState();
if (_isEditing) {
_chapterController.text = widget.excerpt!.chapter;
_contentController.text = widget.excerpt!.content;
_commentController.text = widget.excerpt!.comment;
}
}
@override
void dispose() {
_chapterController.dispose();
_contentController.dispose();
_commentController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(_isEditing ? '编辑摘抄' : '添加摘抄'),
actions: [
TextButton(
onPressed: _isLoading ? null : _saveExcerpt,
child: _isLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text(
'保存',
style: TextStyle(
color: Color(0xFF1A1A1A),
fontWeight: FontWeight.w600,
),
),
),
const SizedBox(width: 8),
],
),
body: Form(
key: _formKey,
child: ListView(
padding: const EdgeInsets.all(24),
children: [
// 章节
TextFormField(
controller: _chapterController,
decoration: const InputDecoration(
labelText: '章节(可选)',
hintText: '例如第一章、第3节等',
border: OutlineInputBorder(
borderRadius: BorderRadius.zero,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.zero,
borderSide: BorderSide(color: Color(0xFF1A1A1A)),
),
),
),
const SizedBox(height: 24),
// 摘抄内容
TextFormField(
controller: _contentController,
maxLines: 8,
decoration: const InputDecoration(
labelText: '摘抄内容',
hintText: '输入你想要摘抄的内容...',
alignLabelWithHint: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.zero,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.zero,
borderSide: BorderSide(color: Color(0xFF1A1A1A)),
),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '请输入摘抄内容';
}
return null;
},
),
const SizedBox(height: 24),
// 评论/感悟
TextFormField(
controller: _commentController,
maxLines: 5,
decoration: const InputDecoration(
labelText: '我的感悟(可选)',
hintText: '记录你对这段内容的思考和感悟...',
alignLabelWithHint: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.zero,
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.zero,
borderSide: BorderSide(color: Color(0xFF1A1A1A)),
),
),
),
],
),
),
);
}
Future<void> _saveExcerpt() async {
if (!_formKey.currentState!.validate()) return;
setState(() => _isLoading = true);
try {
final now = DateTime.now();
final excerpt = BookExcerpt(
id: _isEditing ? widget.excerpt!.id : const Uuid().v4(),
bookId: widget.bookId,
chapter: _chapterController.text.trim(),
content: _contentController.text.trim(),
comment: _commentController.text.trim(),
isDeleted: false,
createdAt: _isEditing ? widget.excerpt!.createdAt : now,
updatedAt: now,
);
if (_isEditing) {
await context.read<AppProvider>().updateBookExcerpt(excerpt);
} else {
await context.read<AppProvider>().addBookExcerpt(excerpt);
}
if (mounted) {
Navigator.pop(context);
ToastUtil.show(context, _isEditing ? '摘抄已更新' : '摘抄已添加');
}
} catch (e) {
if (mounted) {
ToastUtil.show(context, '保存失败: $e');
}
} finally {
if (mounted) {
setState(() => _isLoading = false);
}
}
}
}

View File

@@ -0,0 +1,297 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../utils/toast_util.dart';
import 'book_excerpt_form_page.dart';
/// 书籍摘抄列表页面
class BookExcerptsPage extends StatefulWidget {
final Book book;
const BookExcerptsPage({super.key, required this.book});
@override
State<BookExcerptsPage> createState() => _BookExcerptsPageState();
}
class _BookExcerptsPageState extends State<BookExcerptsPage> {
List<BookExcerpt> _excerpts = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadExcerpts();
}
Future<void> _loadExcerpts() async {
setState(() => _isLoading = true);
try {
final excerpts = await context.read<AppProvider>().getBookExcerpts(widget.book.id);
setState(() {
_excerpts = excerpts;
_isLoading = false;
});
} catch (e) {
setState(() => _isLoading = false);
ToastUtil.show(context, '加载失败: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('摘抄'),
actions: [
IconButton(
icon: const Icon(Icons.add),
onPressed: () => _navigateToAddExcerpt(),
),
const SizedBox(width: 8),
],
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _excerpts.isEmpty
? _buildEmptyState()
: _buildExcerptList(),
);
}
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.format_quote_outlined,
size: 64,
color: Color(0xFFCCCCCC),
),
const SizedBox(height: 16),
const Text(
'暂无摘抄',
style: TextStyle(
fontSize: 16,
color: Color(0xFF999999),
),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: () => _navigateToAddExcerpt(),
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFF1A1A1A),
side: const BorderSide(color: Color(0xFF1A1A1A)),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
),
child: const Text('添加摘抄'),
),
],
),
);
}
/// 按章节分组摘抄数据
Map<String, List<BookExcerpt>> _groupExcerptsByChapter() {
final Map<String, List<BookExcerpt>> groups = {};
for (final excerpt in _excerpts) {
final chapter = excerpt.chapter.isEmpty ? '未分类' : excerpt.chapter;
if (!groups.containsKey(chapter)) {
groups[chapter] = [];
}
groups[chapter]!.add(excerpt);
}
// 每个章节内的摘抄按时间排序(新的在前)
for (final chapter in groups.keys) {
groups[chapter]!.sort((a, b) => b.createdAt.compareTo(a.createdAt));
}
return groups;
}
Widget _buildExcerptList() {
final groups = _groupExcerptsByChapter();
final chapters = groups.keys.toList();
return ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: chapters.length,
itemBuilder: (context, index) {
final chapter = chapters[index];
final excerpts = groups[chapter]!;
return _buildChapterSection(chapter, excerpts);
},
);
}
Widget _buildChapterSection(String chapter, List<BookExcerpt> excerpts) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 章节标题
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
decoration: const BoxDecoration(
color: Color(0xFFF5F5F5),
border: Border(
left: BorderSide(color: Color(0xFF1A1A1A), width: 4),
),
),
child: Text(
chapter,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: Color(0xFF1A1A1A),
),
),
),
const SizedBox(height: 12),
// 该章节下的摘抄列表
...excerpts.map((excerpt) => _buildExcerptItem(excerpt)),
const SizedBox(height: 24),
],
);
}
Widget _buildExcerptItem(BookExcerpt excerpt) {
return Container(
margin: const EdgeInsets.only(bottom: 8),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 摘抄内容
Text(
excerpt.content,
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 14,
color: Color(0xFF1A1A1A),
height: 1.5,
),
),
// 评论/感悟
if (excerpt.comment.isNotEmpty) ...[
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
decoration: const BoxDecoration(
color: Color(0xFFF5F5F5),
),
child: Text(
excerpt.comment,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 12,
color: Color(0xFF666666),
),
),
),
],
const SizedBox(height: 8),
// 底部:时间 + 操作按钮
Row(
children: [
Text(
_formatDate(excerpt.createdAt),
style: const TextStyle(
fontSize: 11,
color: Color(0xFF999999),
),
),
const Spacer(),
// 编辑按钮
GestureDetector(
onTap: () => _navigateToEditExcerpt(excerpt),
child: const Icon(
Icons.edit_outlined,
size: 16,
color: Color(0xFF999999),
),
),
const SizedBox(width: 12),
// 删除按钮
GestureDetector(
onTap: () => _showDeleteDialog(excerpt),
child: const Icon(
Icons.delete_outline,
size: 16,
color: Colors.red,
),
),
],
),
],
),
);
}
String _formatDate(DateTime date) {
return '${date.year}.${date.month.toString().padLeft(2, '0')}.${date.day.toString().padLeft(2, '0')}';
}
void _navigateToAddExcerpt() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookExcerptFormPage(bookId: widget.book.id),
),
).then((_) => _loadExcerpts());
}
void _navigateToEditExcerpt(BookExcerpt excerpt) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookExcerptFormPage(
bookId: widget.book.id,
excerpt: excerpt,
),
),
).then((_) => _loadExcerpts());
}
void _showDeleteDialog(BookExcerpt excerpt) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text('确认删除'),
content: const Text('确定要删除这条摘抄吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () async {
await context.read<AppProvider>().removeBookExcerpt(excerpt.id);
Navigator.pop(context);
_loadExcerpts();
ToastUtil.show(context, '已删除');
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
}

View File

@@ -0,0 +1,779 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../utils/toast_util.dart';
import '../../utils/image_path_helper.dart';
/// 添加/编辑书籍页面 - 紧凑双行布局设计
class BookFormPage extends StatefulWidget {
final Book? book;
final String? initialStatus; // 添加时的默认状态
const BookFormPage({super.key, this.book, this.initialStatus});
@override
State<BookFormPage> createState() => _BookFormPageState();
}
class _BookFormPageState extends State<BookFormPage> {
final _formKey = GlobalKey<FormState>();
final ImagePicker _picker = ImagePicker();
// 输入框控制器
late TextEditingController _titleController;
late TextEditingController _publisherController;
late TextEditingController _summaryController;
late TextEditingController _ratingController;
// 多值字段的临时输入控制器
final Map<String, TextEditingController> _tagControllers = {};
// 数据
List<String> _authors = [];
List<String> _alternateTitles = [];
List<String> _genres = [];
String? _coverPath;
String _status = 'want_to_read';
@override
void initState() {
super.initState();
_initializeData();
}
void _initializeData() {
// 如果有传入book尝试从Provider获取最新数据
Book? book = widget.book;
if (book != null) {
final appProvider = context.read<AppProvider>();
final latestBook = appProvider.books
.where((b) => b.id == book!.id)
.firstOrNull;
if (latestBook != null) {
book = latestBook;
}
}
_titleController = TextEditingController(text: book?.title ?? '');
_publisherController = TextEditingController(text: book?.publisher ?? '');
_summaryController = TextEditingController(text: book?.summary ?? '');
_ratingController = TextEditingController(text: book?.rating?.toString() ?? '');
if (book != null) {
_authors = List.from(book.authors);
_alternateTitles = List.from(book.alternateTitles);
_genres = List.from(book.genres);
_coverPath = book.coverPath;
_status = book.status;
} else if (widget.initialStatus != null) {
// 添加模式:使用传入的默认状态
_status = widget.initialStatus!;
}
}
@override
void dispose() {
_titleController.dispose();
_publisherController.dispose();
_summaryController.dispose();
_ratingController.dispose();
_tagControllers.values.forEach((c) => c.dispose());
super.dispose();
}
TextEditingController _getTagController(String key) {
return _tagControllers.putIfAbsent(key, () => TextEditingController());
}
@override
Widget build(BuildContext context) {
final isEdit = widget.book != null;
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(isEdit ? '编辑书籍' : '添加书籍'),
actions: [
TextButton(
onPressed: _saveBook,
child: const Text(
'保存',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
const SizedBox(width: 8),
],
),
body: Form(
key: _formKey,
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
children: [
// 封面选择 - 居中显示
Center(child: _buildCoverPicker()),
const SizedBox(height: 32),
// 状态选择(靠左显示)
_buildStatusSelector(),
const SizedBox(height: 20),
// 评分 - 星星选择(靠左显示)
_buildStarRating(),
const SizedBox(height: 32),
// 基本信息区域
_buildFormItem(
label: '书名 *',
child: TextFormField(
controller: _titleController,
style: const TextStyle(fontSize: 15, color: Color(0xFF1A1A1A)),
decoration: const InputDecoration(
hintText: '请输入书名',
hintStyle: TextStyle(fontSize: 14, color: Color(0xFFCCCCCC)),
border: InputBorder.none,
contentPadding: EdgeInsets.zero,
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '请输入书名';
}
return null;
},
),
),
_buildDivider(),
// 别名
_buildMultiValueItem(
label: '别名',
values: _alternateTitles,
hint: '输入别名',
controllerKey: 'alternateTitles',
onAdd: (v) => setState(() => _alternateTitles.add(v)),
onRemove: (i) => setState(() => _alternateTitles.removeAt(i)),
),
_buildDivider(),
// 作者
_buildMultiValueItem(
label: '作者',
values: _authors,
hint: '输入作者姓名',
controllerKey: 'authors',
onAdd: (v) => setState(() => _authors.add(v)),
onRemove: (i) => setState(() => _authors.removeAt(i)),
),
_buildDivider(),
// 出版社
_buildFormItem(
label: '出版社',
child: TextFormField(
controller: _publisherController,
style: const TextStyle(fontSize: 15, color: Color(0xFF1A1A1A)),
decoration: const InputDecoration(
hintText: '请输入出版社',
hintStyle: TextStyle(fontSize: 14, color: Color(0xFFCCCCCC)),
border: InputBorder.none,
contentPadding: EdgeInsets.zero,
),
),
),
_buildDivider(),
// 类型
_buildMultiValueItem(
label: '类型',
values: _genres,
hint: '如:小说、历史',
controllerKey: 'genres',
onAdd: (v) => setState(() => _genres.add(v)),
onRemove: (i) => setState(() => _genres.removeAt(i)),
),
_buildDivider(),
// 书籍简介
_buildFormItem(
label: '书籍简介',
child: TextFormField(
controller: _summaryController,
maxLines: 4,
style: const TextStyle(fontSize: 15, color: Color(0xFF1A1A1A), height: 1.5),
decoration: const InputDecoration(
hintText: '写下书籍简介...',
hintStyle: TextStyle(fontSize: 14, color: Color(0xFFCCCCCC)),
border: InputBorder.none,
contentPadding: EdgeInsets.zero,
),
),
),
const SizedBox(height: 48),
],
),
),
);
}
/// 构建表单条目(标签 + 内容)
Widget _buildFormItem({required String label, required Widget child}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 13,
color: label.contains('*') ? const Color(0xFF1A1A1A) : const Color(0xFF666666),
fontWeight: label.contains('*') ? FontWeight.w500 : FontWeight.normal,
),
),
const SizedBox(height: 8),
child,
],
);
}
/// 构建多值条目
Widget _buildMultiValueItem({
required String label,
required List<String> values,
required String hint,
required String controllerKey,
required Function(String) onAdd,
required Function(int) onRemove,
}) {
final controller = _getTagController(controllerKey);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 第一行:标签 + 添加按钮
Row(
children: [
Text(
label,
style: const TextStyle(fontSize: 13, color: Color(0xFF666666)),
),
const Spacer(),
// 添加按钮(当输入框有内容时显示)
ValueListenableBuilder<TextEditingValue>(
valueListenable: controller,
builder: (context, value, child) {
final hasText = value.text.trim().isNotEmpty;
return GestureDetector(
onTap: hasText
? () {
final text = controller.text.trim();
if (text.isNotEmpty && !values.contains(text)) {
onAdd(text);
controller.clear();
}
}
: null,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
border: Border.all(
color: hasText ? const Color(0xFF1A1A1A) : const Color(0xFFE5E5E5),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.add,
size: 14,
color: hasText ? const Color(0xFF1A1A1A) : const Color(0xFFCCCCCC),
),
const SizedBox(width: 2),
Text(
'添加',
style: TextStyle(
fontSize: 12,
color: hasText ? const Color(0xFF1A1A1A) : const Color(0xFFCCCCCC),
),
),
],
),
),
);
},
),
],
),
const SizedBox(height: 8),
// 第二行:已选标签 + 输入框
Wrap(
spacing: 8,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
...values.asMap().entries.map((entry) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
entry.value,
style: const TextStyle(fontSize: 14, color: Color(0xFF1A1A1A)),
),
const SizedBox(width: 4),
GestureDetector(
onTap: () => onRemove(entry.key),
child: const Icon(Icons.close, size: 14, color: Color(0xFF999999)),
),
],
),
);
}),
// 输入框
ConstrainedBox(
constraints: const BoxConstraints(minWidth: 100, maxWidth: 150),
child: TextField(
controller: controller,
style: const TextStyle(fontSize: 14, color: Color(0xFF1A1A1A)),
decoration: InputDecoration(
hintText: values.isEmpty ? hint : '',
hintStyle: const TextStyle(fontSize: 14, color: Color(0xFFCCCCCC)),
border: InputBorder.none,
isDense: true,
contentPadding: const EdgeInsets.symmetric(vertical: 5),
),
onSubmitted: (value) {
final trimmed = value.trim();
if (trimmed.isNotEmpty && !values.contains(trimmed)) {
onAdd(trimmed);
controller.clear();
}
},
),
),
],
),
],
);
}
/// 构建分隔线
Widget _buildDivider() {
return Container(
margin: const EdgeInsets.symmetric(vertical: 16),
height: 0.5,
color: const Color(0xFFE5E5E5),
);
}
/// 构建状态选择器(靠左显示,带标签)
Widget _buildStatusSelector() {
return Row(
children: [
const Text(
'状态',
style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
),
const SizedBox(width: 16),
Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_buildStatusOption('想读', 'want_to_read'),
_buildStatusOption('在读', 'reading'),
_buildStatusOption('已读', 'read'),
],
),
),
],
);
}
/// 构建星星评分5星制每星2分支持手动输入
Widget _buildStarRating() {
return Row(
children: [
const Text(
'评分',
style: TextStyle(fontSize: 14, color: Color(0xFF666666)),
),
const SizedBox(width: 16),
// 星星选择
_buildStarSelector(),
const SizedBox(width: 12),
// 手动输入框
_buildRatingInputField(),
],
);
}
/// 构建星星选择器
Widget _buildStarSelector() {
final currentRating = double.tryParse(_ratingController.text) ?? 0;
final starRating = currentRating / 2;
return Container(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(5, (index) {
final starValue = index + 1;
final scoreValue = starValue * 2;
final isFilled = starValue <= starRating;
final isHalf = starValue == starRating.ceil() && starRating % 1 != 0;
return InkWell(
onTap: () {
setState(() {
_ratingController.text = scoreValue.toString();
});
},
borderRadius: BorderRadius.circular(4),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 4),
child: Icon(
isHalf
? Icons.star_half
: isFilled
? Icons.star
: Icons.star_border,
size: 24,
color: isFilled || isHalf
? const Color(0xFFFFB800)
: const Color(0xFFE5E5E5),
),
),
);
}),
),
);
}
/// 构建评分输入框
Widget _buildRatingInputField() {
return Container(
width: 56,
height: 36,
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
borderRadius: BorderRadius.circular(8),
),
child: TextFormField(
controller: _ratingController,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
color: Color(0xFF1A1A1A),
),
decoration: const InputDecoration(
hintText: '-',
hintStyle: TextStyle(fontSize: 15, color: Color(0xFFCCCCCC)),
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
),
validator: (value) {
if (value != null && value.isNotEmpty) {
final rating = double.tryParse(value);
if (rating == null || rating < 0 || rating > 10) {
return '0-10';
}
}
return null;
},
onChanged: (value) {
// 限制输入范围
if (value.isNotEmpty) {
final rating = double.tryParse(value);
if (rating != null) {
if (rating > 10) {
_ratingController.text = '10';
} else if (rating < 0) {
_ratingController.text = '0';
}
}
}
setState(() {}); // 更新星星显示
},
),
);
}
/// 构建状态选项
Widget _buildStatusOption(String label, String value) {
final isSelected = _status == value;
return GestureDetector(
onTap: () => setState(() => _status = value),
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
decoration: BoxDecoration(
color: isSelected ? Colors.white : Colors.transparent,
borderRadius: BorderRadius.circular(6),
boxShadow: isSelected
? [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 4,
offset: const Offset(0, 2),
),
]
: null,
),
child: Text(
label,
style: TextStyle(
fontSize: 14,
fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
color: isSelected ? const Color(0xFF1A1A1A) : const Color(0xFF999999),
),
),
),
);
}
/// 构建封面选择器
Widget _buildCoverPicker() {
final hasCover = _coverPath != null && _coverPath!.isNotEmpty;
return Column(
children: [
GestureDetector(
onTap: _pickCover,
child: Container(
width: 140,
height: 200,
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5), width: 0.5),
),
child: hasCover
? Image.file(
File(_coverPath!),
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => _buildCoverPlaceholder(),
)
: _buildCoverPlaceholder(),
),
),
// 清空封面按钮(仅当有封面时显示)
if (hasCover)
Padding(
padding: const EdgeInsets.only(top: 12),
child: GestureDetector(
onTap: () => setState(() => _coverPath = null),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.hide_image_outlined,
size: 16,
color: Color(0xFF666666),
),
SizedBox(width: 4),
Text(
'清空封面',
style: TextStyle(
fontSize: 13,
color: Color(0xFF666666),
),
),
],
),
),
),
),
],
);
}
Widget _buildCoverPlaceholder() {
return const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.add_photo_alternate_outlined,
size: 40,
color: Color(0xFF999999),
),
SizedBox(height: 12),
Text(
'点击添加封面',
style: TextStyle(
fontSize: 14,
color: Color(0xFF999999),
),
),
],
);
}
/// 选择封面
Future<void> _pickCover() async {
try {
final XFile? pickedFile = await _picker.pickImage(
source: ImageSource.gallery,
maxWidth: 800,
maxHeight: 1200,
imageQuality: 85,
);
if (pickedFile != null) {
// 生成文件名
final fileName = 'cover_${DateTime.now().millisecondsSinceEpoch}.jpg';
// 如果是编辑模式使用现有书籍ID如果是新建模式使用临时ID保存时会替换
final bookId = widget.book?.id ?? DateTime.now().millisecondsSinceEpoch.toString();
// 保存到新的路径结构: images/books/{bookId}/{fileName}
final targetPath = await ImagePathHelper.instance.getBookCoverPath(
bookId,
fileName
);
await ImagePathHelper.instance.ensureDirExists(p.dirname(targetPath));
await File(pickedFile.path).copy(targetPath);
setState(() => _coverPath = targetPath);
}
} catch (e) {
if (mounted) {
ToastUtil.show(context, '选择封面失败: $e');
}
}
}
/// 保存书籍
Future<void> _saveBook() async {
if (!_formKey.currentState!.validate()) {
return;
}
final rating = _ratingController.text.isNotEmpty
? double.tryParse(_ratingController.text)
: null;
final now = DateTime.now();
if (widget.book == null) {
// 生成新的书籍ID
final newBookId = now.millisecondsSinceEpoch.toString();
// 如果有封面需要移动到正确的ID目录
String? finalCoverPath;
if (_coverPath != null && _coverPath!.isNotEmpty) {
finalCoverPath = await _moveCoverToNewId(_coverPath!, newBookId);
}
final newBook = Book(
id: newBookId,
title: _titleController.text.trim(),
coverPath: finalCoverPath,
authors: _authors,
alternateTitles: _alternateTitles,
publisher: _publisherController.text.trim(),
genres: _genres,
summary: _summaryController.text.trim(),
rating: rating,
status: _status,
createdAt: now,
updatedAt: now,
);
await context.read<AppProvider>().addBook(newBook);
} else {
final updatedBook = widget.book!.copyWith(
title: _titleController.text.trim(),
coverPath: _coverPath,
authors: _authors,
alternateTitles: _alternateTitles,
publisher: _publisherController.text.trim(),
genres: _genres,
summary: _summaryController.text.trim(),
rating: rating,
status: _status,
updatedAt: now,
);
await context.read<AppProvider>().updateBook(updatedBook);
}
if (!mounted) return;
ToastUtil.show(context, widget.book == null ? '添加成功' : '更新成功');
Navigator.pop(context);
}
/// 将封面从临时ID目录移动到新的书籍ID目录
Future<String?> _moveCoverToNewId(String currentPath, String newBookId) async {
// 检查是否已经在正确的目录中(兼容 Windows 路径分隔符)
final normalizedPath = currentPath.replaceAll('\\', '/');
if (normalizedPath.contains('/books/$newBookId/')) {
return currentPath;
}
// 提取文件名
final fileName = p.basename(currentPath);
// 获取新路径
final newPath = await ImagePathHelper.instance.getBookCoverPath(
newBookId,
fileName
);
// 确保目标目录存在
await ImagePathHelper.instance.ensureDirExists(p.dirname(newPath));
// 移动文件
final currentFile = File(currentPath);
if (await currentFile.exists()) {
await currentFile.rename(newPath);
// 删除空的临时目录
final tempDir = Directory(p.dirname(currentPath));
if (await tempDir.exists()) {
try {
await tempDir.delete(recursive: true);
} catch (e) {
// 忽略删除目录失败的情况
}
}
return newPath;
}
return null;
}
}

View File

@@ -0,0 +1,262 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../utils/toast_util.dart';
import 'package:uuid/uuid.dart';
/// 添加/编辑书评页面 - 极简设计
class BookReviewFormPage extends StatefulWidget {
final String bookId;
final BookReview? review;
const BookReviewFormPage({
super.key,
required this.bookId,
this.review,
});
@override
State<BookReviewFormPage> createState() => _BookReviewFormPageState();
}
class _BookReviewFormPageState extends State<BookReviewFormPage> {
final _formKey = GlobalKey<FormState>();
late TextEditingController _contentController;
late TextEditingController _reviewerController;
late TextEditingController _sourceController;
late int _reviewType;
@override
void initState() {
super.initState();
final review = widget.review;
_contentController = TextEditingController(text: review?.content ?? '');
_reviewerController = TextEditingController(text: review?.reviewer ?? '');
_sourceController = TextEditingController(text: review?.source ?? '');
_reviewType = review?.reviewType ?? 1;
}
@override
void dispose() {
_contentController.dispose();
_reviewerController.dispose();
_sourceController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final isEdit = widget.review != null;
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(isEdit ? '编辑书评' : '写书评'),
actions: [
TextButton(
onPressed: _saveReview,
child: const Text(
'保存',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
const SizedBox(width: 8),
],
),
body: Form(
key: _formKey,
child: Column(
children: [
// 顶部信息栏
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(color: Color(0xFFE5E5E5), width: 0.5),
),
),
child: Row(
children: [
// 类型选择
_buildTypeSelector(),
const SizedBox(width: 16),
// 评论人
Expanded(
child: TextField(
controller: _reviewerController,
style: const TextStyle(fontSize: 14, color: Color(0xFF1A1A1A)),
decoration: const InputDecoration(
hintText: '评论人',
hintStyle: TextStyle(fontSize: 14, color: Color(0xFFCCCCCC)),
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.zero,
),
),
),
const SizedBox(width: 16),
// 来源
SizedBox(
width: 100,
child: TextField(
controller: _sourceController,
style: const TextStyle(fontSize: 14, color: Color(0xFF1A1A1A)),
decoration: const InputDecoration(
hintText: '来源',
hintStyle: TextStyle(fontSize: 14, color: Color(0xFFCCCCCC)),
border: InputBorder.none,
isDense: true,
contentPadding: EdgeInsets.zero,
),
),
),
],
),
),
// 评论内容区域
Expanded(
child: TextFormField(
controller: _contentController,
maxLines: null,
expands: true,
textAlignVertical: TextAlignVertical.top,
style: const TextStyle(
fontSize: 16,
color: Color(0xFF1A1A1A),
height: 1.7,
),
decoration: const InputDecoration(
hintText: '写下你的书评...',
hintStyle: TextStyle(
fontSize: 16,
color: Color(0xFFCCCCCC),
),
border: InputBorder.none,
contentPadding: EdgeInsets.all(16),
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return '请输入评论内容';
}
return null;
},
),
),
],
),
),
);
}
/// 构建类型选择器
Widget _buildTypeSelector() {
return GestureDetector(
onTap: () => _showTypeSelector(),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_reviewType == 1 ? '短评' : '长评',
style: const TextStyle(
fontSize: 13,
color: Color(0xFF666666),
),
),
const SizedBox(width: 4),
const Icon(
Icons.arrow_drop_down,
size: 16,
color: Color(0xFF999999),
),
],
),
),
);
}
/// 显示类型选择
void _showTypeSelector() {
showModalBottomSheet(
context: context,
backgroundColor: Colors.white,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: const Text('短评'),
trailing: _reviewType == 1
? const Icon(Icons.check, color: Color(0xFF1A1A1A))
: null,
onTap: () {
setState(() => _reviewType = 1);
Navigator.pop(context);
},
),
const Divider(height: 0.5),
ListTile(
title: const Text('长评'),
trailing: _reviewType == 2
? const Icon(Icons.check, color: Color(0xFF1A1A1A))
: null,
onTap: () {
setState(() => _reviewType = 2);
Navigator.pop(context);
},
),
],
),
),
);
}
Future<void> _saveReview() async {
if (!_formKey.currentState!.validate()) {
return;
}
final now = DateTime.now();
if (widget.review == null) {
final newReview = BookReview(
id: const Uuid().v4(),
bookId: widget.bookId,
content: _contentController.text.trim(),
reviewer: _reviewerController.text.trim(),
source: _sourceController.text.trim(),
reviewType: _reviewType,
isDeleted: false,
createdAt: now,
updatedAt: now,
);
await context.read<AppProvider>().addBookReview(newReview);
} else {
final updatedReview = widget.review!.copyWith(
content: _contentController.text.trim(),
reviewer: _reviewerController.text.trim(),
source: _sourceController.text.trim(),
reviewType: _reviewType,
updatedAt: now,
);
await context.read<AppProvider>().updateBookReview(updatedReview);
}
if (!mounted) return;
ToastUtil.show(context, widget.review == null ? '添加成功' : '更新成功');
Navigator.pop(context);
}
}

View File

@@ -0,0 +1,270 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../utils/toast_util.dart';
import 'book_review_form_page.dart';
/// 书籍书评列表页面
class BookReviewsPage extends StatefulWidget {
final Book book;
const BookReviewsPage({super.key, required this.book});
@override
State<BookReviewsPage> createState() => _BookReviewsPageState();
}
class _BookReviewsPageState extends State<BookReviewsPage> {
List<BookReview> _reviews = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadReviews();
}
Future<void> _loadReviews() async {
setState(() => _isLoading = true);
try {
final reviews = await context.read<AppProvider>().getBookReviews(widget.book.id);
setState(() {
_reviews = reviews;
_isLoading = false;
});
} catch (e) {
setState(() => _isLoading = false);
ToastUtil.show(context, '加载失败: $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('书评'),
actions: [
IconButton(
icon: const Icon(Icons.add),
onPressed: () => _navigateToAddReview(),
),
const SizedBox(width: 8),
],
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _reviews.isEmpty
? _buildEmptyState()
: _buildReviewList(),
);
}
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.rate_review_outlined,
size: 64,
color: Color(0xFFCCCCCC),
),
const SizedBox(height: 16),
const Text(
'暂无书评',
style: TextStyle(
fontSize: 16,
color: Color(0xFF999999),
),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: () => _navigateToAddReview(),
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFF1A1A1A),
side: const BorderSide(color: Color(0xFF1A1A1A)),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
),
child: const Text('写书评'),
),
],
),
);
}
Widget _buildReviewList() {
return ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: _reviews.length,
itemBuilder: (context, index) {
final review = _reviews[index];
return _buildReviewItem(review);
},
);
}
Widget _buildReviewItem(BookReview review) {
return InkWell(
onLongPress: () => _showDeleteDialog(review),
child: Container(
margin: const EdgeInsets.only(bottom: 16),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 头部:类型标签 + 操作按钮
Row(
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: review.reviewType == 1
? const Color(0xFFF5F5F5)
: const Color(0xFF1A1A1A),
),
child: Text(
review.typeText,
style: TextStyle(
fontSize: 11,
color: review.reviewType == 1
? const Color(0xFF666666)
: Colors.white,
),
),
),
const Spacer(),
// 编辑按钮
GestureDetector(
onTap: () => _navigateToEditReview(review),
child: const Icon(
Icons.edit_outlined,
size: 18,
color: Color(0xFF999999),
),
),
const SizedBox(width: 16),
// 删除按钮
GestureDetector(
onTap: () => _showDeleteDialog(review),
child: const Icon(
Icons.delete_outline,
size: 18,
color: Colors.red,
),
),
],
),
const SizedBox(height: 12),
// 评论内容
Text(
review.content,
maxLines: review.reviewType == 1 ? 3 : 5,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontSize: 15,
color: Color(0xFF1A1A1A),
height: 1.6,
),
),
const SizedBox(height: 12),
// 底部信息
Row(
children: [
if (review.reviewer.isNotEmpty) ...[
Text(
review.reviewer,
style: const TextStyle(
fontSize: 13,
color: Color(0xFF666666),
),
),
const SizedBox(width: 8),
],
if (review.source.isNotEmpty) ...[
Text(
'来源:${review.source}',
style: const TextStyle(
fontSize: 12,
color: Color(0xFF999999),
),
),
const SizedBox(width: 8),
],
const Spacer(),
Text(
_formatDate(review.createdAt),
style: const TextStyle(
fontSize: 12,
color: Color(0xFF999999),
),
),
],
),
],
),
),
);
}
String _formatDate(DateTime date) {
return '${date.year}.${date.month.toString().padLeft(2, '0')}.${date.day.toString().padLeft(2, '0')}';
}
void _navigateToAddReview() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookReviewFormPage(bookId: widget.book.id),
),
).then((_) => _loadReviews());
}
void _navigateToEditReview(BookReview review) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BookReviewFormPage(
bookId: widget.book.id,
review: review,
),
),
).then((_) => _loadReviews());
}
void _showDeleteDialog(BookReview review) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text('确认删除'),
content: const Text('确定要删除这条书评吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () async {
await context.read<AppProvider>().removeBookReview(review.id);
Navigator.pop(context);
_loadReviews();
ToastUtil.show(context, '已删除');
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
}

View File

@@ -0,0 +1,174 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../widgets/book_status_bar.dart';
import '../../widgets/book_list_item.dart';
/// 阅读标签页
class BookTabPage extends StatelessWidget {
const BookTabPage({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
// 状态选择栏(读完、在读、准备读)
const BookStatusBar(),
// 书籍列表
Expanded(
child: _buildBookList(context),
),
],
);
}
/// 构建书籍列表
Widget _buildBookList(BuildContext context) {
return Consumer<AppProvider>(
builder: (context, provider, child) {
// 根据状态筛选书籍
final statusMap = {
0: 'read',
1: 'reading',
2: 'want_to_read',
};
final currentStatus = statusMap[provider.bookStatusIndex]!;
final books = provider.getBooksByStatus(currentStatus);
if (books.isEmpty) {
return _buildEmptyState(context, provider.bookStatusIndex);
}
return RefreshIndicator(
onRefresh: () async => await provider.loadBooks(),
color: const Color(0xFF1A1A1A),
backgroundColor: Colors.white,
child: GridView.builder(
padding: const EdgeInsets.all(16),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: 0.55,
crossAxisSpacing: 12,
mainAxisSpacing: 16,
),
itemCount: books.length,
itemBuilder: (context, index) {
return BookListItem(book: books[index]);
},
),
);
},
);
}
/// 构建空状态提示
Widget _buildEmptyState(BuildContext context, int statusIndex) {
final statusText = ['读完', '在读', '准备读'][statusIndex];
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.menu_book_outlined,
size: 80,
color: Theme.of(context).colorScheme.onSurfaceVariant.withValues(alpha: 0.3),
),
const SizedBox(height: 16),
Text(
'暂无$statusText的书籍',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
ElevatedButton.icon(
icon: const Icon(Icons.add),
label: const Text('添加记录'),
onPressed: () {
final statusMap = {
0: 'read',
1: 'reading',
2: 'want_to_read',
};
final currentStatus = statusMap[statusIndex]!;
Navigator.pushNamed(
context,
'/book-form',
arguments: {'initialStatus': currentStatus},
);
},
),
],
),
);
}
/// 获取示例书籍数据
List<Book> _getSampleBooks(int statusIndex) {
final statusMap = ['read', 'reading', 'want_to_read'];
final currentStatus = statusMap[statusIndex];
final now = DateTime.now();
// 示例数据(实际应从数据库获取)
final allBooks = [
Book(
id: '1',
title: '活着',
authors: ['余华'],
rating: 9.2,
status: 'read',
genres: ['小说', '文学'],
summary: '非常感人的故事,让人思考生命的意义',
createdAt: now,
updatedAt: now,
),
Book(
id: '2',
title: '百年孤独',
authors: ['加西亚·马尔克斯'],
rating: 9.3,
status: 'read',
genres: ['小说', '魔幻现实主义'],
publisher: '南海出版公司',
createdAt: now,
updatedAt: now,
),
Book(
id: '3',
title: '人类简史',
authors: ['尤瓦尔·赫拉利'],
rating: 9.0,
status: 'reading',
genres: ['历史', '科普'],
createdAt: now,
updatedAt: now,
),
Book(
id: '4',
title: '三体',
authors: ['刘慈欣'],
rating: 9.5,
status: 'want_to_read',
genres: ['科幻', '小说'],
createdAt: now,
updatedAt: now,
),
Book(
id: '5',
title: '追风筝的人',
authors: ['卡勒德·胡赛尼'],
rating: 8.9,
status: 'read',
genres: ['小说', '文学'],
summary: '关于救赎与成长的故事',
createdAt: now,
updatedAt: now,
),
];
return allBooks.where((b) => b.status == currentStatus).toList();
}
}