Initial commit: Flutter 无书应用项目

This commit is contained in:
Developer
2026-03-30 02:35:31 +08:00
commit 9175ff9905
566 changed files with 103261 additions and 0 deletions

View File

@@ -0,0 +1,663 @@
import 'dart:ui';
import 'dart:async';
import 'package:flutter/material.dart';
import '../../constants/app_constants.dart';
import '../../controllers/history_controller.dart';
import '../../services/network_listener_service.dart';
import '../../utils/http/poetry_api.dart';
import 'collect_notes.dart';
import 'liked_poetry_manager.dart';
/// 时间: 2026-03-26
/// 功能: 全部收藏列表组件
/// 介绍: 同时展示点赞诗词和笔记,支持多种卡片类型
/// 最新变化: 新建组件,统一展示所有收藏内容
/// 卡片类型枚举
enum CardType { like, note }
/// 统一卡片数据模型
class UnifiedCard {
final CardType type;
final dynamic data;
final DateTime time;
UnifiedCard({required this.type, required this.data, required this.time});
}
class AllListPage extends StatefulWidget {
const AllListPage({super.key});
@override
State<AllListPage> createState() => _AllListPageState();
}
class _AllListPageState extends State<AllListPage> {
List<UnifiedCard> _cards = [];
bool _isLoading = false;
StreamSubscription<NetworkEvent>? _networkSubscription;
@override
void initState() {
super.initState();
_loadAllData();
_listenToNetworkEvents();
}
@override
void dispose() {
_networkSubscription?.cancel();
super.dispose();
}
// 监听网络事件,实时更新列表
void _listenToNetworkEvents() {
_networkSubscription = NetworkListenerService().eventStream.listen((event) {
if (event.type == NetworkEventType.like ||
event.type == NetworkEventType.unlike ||
event.type == NetworkEventType.noteUpdate) {
debugPrint('AllListPage: 收到事件 ${event.type},刷新列表');
_loadAllData();
}
});
}
// 加载所有数据
Future<void> _loadAllData() async {
if (_isLoading) return;
setState(() {
_isLoading = true;
});
try {
final List<UnifiedCard> allCards = [];
// 并行加载点赞和笔记数据
final results = await Future.wait([
HistoryController.getLikedHistory(),
HistoryController.getNotes(),
]);
// 处理点赞数据
final likedList = results[0];
for (final item in likedList) {
try {
final poetry = PoetryData.fromJson(item);
final timeStr = item['time'] as String? ?? '';
allCards.add(
UnifiedCard(
type: CardType.like,
data: poetry,
time: DateTime.tryParse(timeStr) ?? DateTime.now(),
),
);
} catch (e) {
debugPrint('解析点赞数据失败: $e');
}
}
// 处理笔记数据
final notesList = results[1];
for (final note in notesList) {
final timeStr = note['time'] as String? ?? '';
allCards.add(
UnifiedCard(
type: CardType.note,
data: note,
time: DateTime.tryParse(timeStr) ?? DateTime.now(),
),
);
}
// 按时间排序(最新的在前)
allCards.sort((a, b) => b.time.compareTo(a.time));
if (mounted) {
setState(() {
_cards = allCards;
_isLoading = false;
});
}
} catch (e) {
debugPrint('加载全部数据失败: $e');
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
if (_isLoading && _cards.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (_cards.isEmpty) {
return _buildEmptyState();
}
return RefreshIndicator(
onRefresh: _loadAllData,
child: ListView.builder(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 80),
itemCount: _cards.length + 1,
itemBuilder: (context, index) {
if (index == _cards.length) {
return _buildBottomIndicator();
}
return _buildCard(_cards[index]);
},
),
);
}
Widget _buildBottomIndicator() {
return Container(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(width: 40, height: 1, color: Colors.grey[300]),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'到底了',
style: TextStyle(fontSize: 12, color: Colors.grey[400]),
),
),
Container(width: 40, height: 1, color: Colors.grey[300]),
],
),
);
}
// 构建空状态
Widget _buildEmptyState() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.inbox_outlined, size: 64, color: Colors.grey[400]),
const SizedBox(height: 16),
Text(
'暂无收藏内容',
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
const SizedBox(height: 8),
Text(
'点赞诗词或创建笔记后将显示在这里',
style: TextStyle(fontSize: 14, color: Colors.grey[500]),
),
],
),
);
}
// 根据类型构建卡片 - 使用策略模式
Widget _buildCard(UnifiedCard card) {
switch (card.type) {
case CardType.like:
return _buildLikeCard(card.data as PoetryData);
case CardType.note:
return _buildNoteCard(card.data as Map<String, dynamic>);
}
}
// 构建点赞卡片 - 简洁紧凑样式
Widget _buildLikeCard(PoetryData poetry) {
return Container(
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: AppConstants.primaryColor.withValues(alpha: 0.2),
width: 1,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.03),
blurRadius: 6,
offset: const Offset(0, 1),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 顶部行:出处(左) + 标签(右)
Padding(
padding: const EdgeInsets.fromLTRB(10, 4, 0, 4),
child: Row(
children: [
// 出处 - 左上角
if (poetry.url.isNotEmpty)
Expanded(
child: Text(
poetry.url,
style: TextStyle(fontSize: 11, color: Colors.grey[600]),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
if (poetry.url.isEmpty) const Spacer(),
// 类型标识 - 右上角
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: AppConstants.primaryColor.withValues(alpha: 0.1),
borderRadius: const BorderRadius.only(
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.favorite,
size: 12,
color: AppConstants.primaryColor,
),
const SizedBox(width: 3),
Text(
'点赞诗词',
style: TextStyle(
fontSize: 11,
color: AppConstants.primaryColor,
fontWeight: FontWeight.w500,
),
),
],
),
),
],
),
),
// 诗句内容
Padding(
padding: const EdgeInsets.fromLTRB(10, 4, 10, 4),
child: Text(
poetry.name,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.black87,
height: 1.3,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
// 操作按钮
Padding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 6),
child: Row(
children: [
TextButton.icon(
onPressed: () => _showPoetryDetails(poetry),
icon: Icon(
Icons.visibility,
size: 14,
color: AppConstants.primaryColor,
),
label: Text(
'查看详情',
style: TextStyle(
fontSize: 12,
color: AppConstants.primaryColor,
),
),
),
const Spacer(),
TextButton.icon(
onPressed: () => _createNoteFromPoetry(poetry),
icon: Icon(
Icons.note_add,
size: 14,
color: Colors.orange[700],
),
label: Text(
'创建笔记',
style: TextStyle(fontSize: 12, color: Colors.orange[700]),
),
),
TextButton.icon(
onPressed: () => _removeLikedPoetry(poetry.id.toString()),
icon: Icon(
Icons.favorite_border,
size: 14,
color: Colors.grey[600],
),
label: Text(
'取消',
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
),
],
),
),
],
),
);
}
// 构建笔记卡片 - 紧凑阴影样式
Widget _buildNoteCard(Map<String, dynamic> note) {
final title = note['title'] as String? ?? '';
final content = note['content'] as String? ?? '';
final category = note['category'] as String? ?? '';
final isPinned = note['isPinned'] == true;
final isLocked = note['isLocked'] == true;
String displayText;
bool hasTitle = title.isNotEmpty;
bool hasCategory = category.isNotEmpty && category != '未分类';
if (hasTitle) {
displayText = title;
} else if (hasCategory) {
displayText = '[$category]';
} else {
displayText = content;
}
return Container(
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.06),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 笔记内容
InkWell(
onTap: () => _handleNoteTap(note, isLocked),
borderRadius: BorderRadius.circular(10),
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 28, 10, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
displayText,
style: TextStyle(
fontSize: hasTitle ? 14 : 13,
fontWeight: hasTitle
? FontWeight.w600
: FontWeight.normal,
color: Colors.black87,
height: 1.4,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Row(
children: [
Text(
'${note['charCount'] ?? displayText.length}',
style: TextStyle(
fontSize: 11,
color: Colors.grey[500],
),
),
if (hasCategory) ...[
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 1,
),
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(3),
),
child: Text(
category,
style: TextStyle(
fontSize: 9,
color: Colors.grey[600],
),
),
),
],
],
),
],
),
),
),
],
),
// 类型标识 - 右上角
Positioned(
top: 0,
right: 0,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Colors.orange.withValues(alpha: 0.1),
borderRadius: const BorderRadius.only(
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.note_outlined,
size: 12,
color: Colors.orange[700],
),
const SizedBox(width: 3),
Text(
'笔记',
style: TextStyle(
fontSize: 11,
color: Colors.orange[700],
fontWeight: FontWeight.w500,
),
),
if (isPinned) ...[
const SizedBox(width: 6),
Icon(Icons.push_pin, size: 10, color: Colors.orange[700]),
],
if (isLocked) ...[
const SizedBox(width: 6),
Icon(Icons.lock, size: 10, color: Colors.orange[700]),
],
],
),
),
),
// 锁定遮罩
if (isLocked)
Positioned.fill(
child: GestureDetector(
onTap: () => _handleNoteTap(note, isLocked),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: Container(
color: Colors.white.withValues(alpha: 0.4),
child: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.lock,
size: 16,
color: Colors.orange[700],
),
const SizedBox(width: 6),
Text(
'已锁定',
style: TextStyle(
fontSize: 13,
color: Colors.orange[700],
fontWeight: FontWeight.w500,
),
),
],
),
),
),
),
),
),
),
],
),
);
}
// 显示诗词详情 - 调用公共方法
Future<void> _showPoetryDetails(PoetryData poetry) async {
await LikedPoetryManager.showPoetryDetails(context, poetry);
}
// 移除点赞
Future<void> _removeLikedPoetry(String poetryId) async {
try {
await HistoryController.removeLikedPoetry(poetryId);
await _loadAllData();
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('已取消点赞')));
}
} catch (e) {
debugPrint('取消点赞失败: $e');
}
}
// 从诗词创建笔记
Future<void> _createNoteFromPoetry(PoetryData poetry) async {
try {
final title = poetry.url.isNotEmpty ? poetry.url : '诗词笔记';
final category = poetry.alias.isNotEmpty ? poetry.alias : '诗词';
final content = poetry.name;
final noteId = await HistoryController.saveNote(
title: title,
content: content,
category: category,
);
if (noteId != null) {
NetworkListenerService().sendSuccessEvent(
NetworkEventType.noteUpdate,
data: noteId,
);
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('已创建笔记')));
}
}
} catch (e) {
debugPrint('创建笔记失败: $e');
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('创建笔记失败: $e')));
}
}
}
// 处理笔记点击
Future<void> _handleNoteTap(Map<String, dynamic> note, bool isLocked) async {
final noteId = note['id'] as String?;
if (noteId == null) return;
if (isLocked) {
final password = await _showPasswordInputDialog(noteId);
if (password == null) return;
final isValid = await HistoryController.verifyNotePassword(
noteId,
password,
);
if (!isValid) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('密码错误')));
}
return;
}
}
if (mounted) {
Navigator.of(context)
.push(
MaterialPageRoute<void>(
builder: (_) => CollectNotesPage(noteId: noteId),
),
)
.then((_) => _loadAllData());
}
}
// 密码输入对话框
Future<String?> _showPasswordInputDialog(String noteId) async {
final TextEditingController passwordController = TextEditingController();
return showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: const Row(
children: [
Icon(Icons.lock, size: 20),
SizedBox(width: 8),
Text('输入密码'),
],
),
content: TextField(
controller: passwordController,
obscureText: true,
autofocus: true,
decoration: const InputDecoration(
hintText: '请输入访问密码',
border: OutlineInputBorder(),
),
onSubmitted: (value) => Navigator.of(context).pop(value),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(null),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(passwordController.text),
child: const Text('确定'),
),
],
),
);
}
}

View File

@@ -0,0 +1,945 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../constants/app_constants.dart';
import '../../controllers/history_controller.dart';
import '../../services/network_listener_service.dart';
/// 时间: 2026-03-26
/// 功能: 笔记编辑页面
/// 介绍: 支持创建和编辑笔记,实时保存到本地存储
/// 最新变化: 实时保存,显示保存时间和字数,支持置顶、密码锁定和分类
class CollectNotesPage extends StatefulWidget {
final String? noteId;
const CollectNotesPage({super.key, this.noteId});
@override
State<CollectNotesPage> createState() => _CollectNotesPageState();
}
class _CollectNotesPageState extends State<CollectNotesPage> {
final TextEditingController _titleController = TextEditingController();
final TextEditingController _contentController = TextEditingController();
final FocusNode _titleFocusNode = FocusNode();
final FocusNode _contentFocusNode = FocusNode();
String? _currentNoteId;
DateTime? _lastSavedTime;
DateTime? _createTime;
int _charCount = 0;
bool _isLoading = true;
bool _isPinned = false;
bool _isLocked = false;
String? _password;
String? _category;
Timer? _debounceTimer;
// 分类选项
final List<String> _categoryOptions = ['未分类', '工作', '学习', '生活', '灵感', '待办'];
// 自定义分类标记
static const String _customCategoryKey = '__custom__';
@override
void initState() {
super.initState();
_currentNoteId = widget.noteId;
_loadNote();
_titleController.addListener(_onContentChanged);
_contentController.addListener(_onContentChanged);
// 监听焦点变化以更新边框颜色
_titleFocusNode.addListener(_onFocusChange);
_contentFocusNode.addListener(_onFocusChange);
}
void _onFocusChange() {
setState(() {});
}
@override
void dispose() {
_debounceTimer?.cancel();
_titleController.removeListener(_onContentChanged);
_contentController.removeListener(_onContentChanged);
_titleFocusNode.removeListener(_onFocusChange);
_contentFocusNode.removeListener(_onFocusChange);
_titleController.dispose();
_contentController.dispose();
_titleFocusNode.dispose();
_contentFocusNode.dispose();
super.dispose();
}
// 加载笔记数据
Future<void> _loadNote() async {
if (_currentNoteId == null) {
setState(() {
_isLoading = false;
_category = _categoryOptions[0];
});
return;
}
try {
final note = await HistoryController.getNote(_currentNoteId!);
if (note != null && note.isNotEmpty) {
_titleController.text = note['title'] ?? '';
_contentController.text = note['content'] ?? '';
_lastSavedTime = DateTime.tryParse(note['time'] ?? '');
_createTime = DateTime.tryParse(note['createTime'] ?? '');
_charCount =
note['charCount'] ??
(_titleController.text.length + _contentController.text.length);
_isPinned = note['isPinned'] ?? false;
_isLocked = note['isLocked'] ?? false;
_password = note['password'];
_category = note['category'] ?? _categoryOptions[0];
}
} catch (e) {
print('加载笔记失败: $e');
}
setState(() {
_isLoading = false;
});
}
// 内容变化时触发防抖保存
void _onContentChanged() {
final newCharCount =
_titleController.text.length + _contentController.text.length;
if (newCharCount != _charCount) {
setState(() {
_charCount = newCharCount;
});
}
_debounceTimer?.cancel();
_debounceTimer = Timer(const Duration(milliseconds: 500), _saveNote);
}
// 保存笔记
Future<void> _saveNote() async {
final title = _titleController.text.trim();
final content = _contentController.text.trim();
if (title.isEmpty && content.isEmpty) {
return;
}
try {
final noteId = await HistoryController.saveNote(
noteId: _currentNoteId,
title: title,
content: content,
isPinned: _isPinned,
isLocked: _isLocked,
password: _password,
category: _category,
createTime: _createTime?.toIso8601String(),
);
if (noteId != null) {
_currentNoteId = noteId;
_lastSavedTime = DateTime.now();
if (_createTime == null) {
_createTime = _lastSavedTime;
}
setState(() {});
print('笔记已自动保存');
NetworkListenerService().sendSuccessEvent(
NetworkEventType.noteUpdate,
data: noteId,
);
}
} catch (e) {
print('保存笔记失败: $e');
}
}
// 切换置顶状态
Future<void> _togglePin() async {
if (_currentNoteId == null) {
final title = _titleController.text.trim();
final content = _contentController.text.trim();
if (title.isEmpty && content.isEmpty) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('请先输入内容')));
return;
}
await _saveNote();
}
setState(() {
_isPinned = !_isPinned;
});
await _saveNote();
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(_isPinned ? '已置顶' : '已取消置顶')));
}
}
// 验证密码格式(只能数字和字母)
bool _isValidPassword(String password) {
final regex = RegExp(r'^[a-zA-Z0-9]+$');
return regex.hasMatch(password);
}
// 显示密码设置对话框
Future<void> _showPasswordDialog() async {
if (_password != null && _password!.isNotEmpty) {
final action = await showDialog<String>(
context: context,
builder: (context) => AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
title: Row(
children: [
Icon(Icons.lock, color: AppConstants.primaryColor, size: 24),
const SizedBox(width: 8),
const Text('锁定设置'),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.vpn_key, size: 16, color: Colors.grey[600]),
const SizedBox(width: 8),
Text(
'当前密码: $_password',
style: TextStyle(
color: Colors.grey[700],
fontSize: 13,
fontWeight: FontWeight.w500,
),
),
],
),
),
const SizedBox(height: 20),
// 取消锁定选项
InkWell(
onTap: () => Navigator.of(context).pop('remove'),
borderRadius: BorderRadius.circular(12),
child: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
vertical: 14,
horizontal: 16,
),
decoration: BoxDecoration(
color: Colors.red[50],
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.red[200]!),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.lock_open, color: Colors.red[400], size: 22),
const SizedBox(width: 10),
Text(
'取消锁定',
style: TextStyle(
color: Colors.red[400],
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
const SizedBox(height: 12),
// 修改密码选项
InkWell(
onTap: () => Navigator.of(context).pop('modify'),
borderRadius: BorderRadius.circular(12),
child: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
vertical: 14,
horizontal: 16,
),
decoration: BoxDecoration(
color: AppConstants.primaryColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: AppConstants.primaryColor.withOpacity(0.3),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.edit,
color: AppConstants.primaryColor,
size: 22,
),
const SizedBox(width: 10),
Text(
'修改密码',
style: TextStyle(
color: AppConstants.primaryColor,
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
],
),
),
);
if (action == null) return;
if (action == 'remove') {
await _removePassword();
return;
}
if (action == 'modify') {
await _showModifyPasswordDialog();
return;
}
} else {
await _showSetPasswordDialog();
}
}
// 显示修改密码对话框
Future<void> _showModifyPasswordDialog() async {
final TextEditingController passwordController = TextEditingController();
final TextEditingController confirmPasswordController =
TextEditingController();
await showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('修改密码'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: '新密码',
hintText: '只能输入数字和字母',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
TextField(
controller: confirmPasswordController,
obscureText: true,
decoration: const InputDecoration(
labelText: '确认密码',
hintText: '再次输入新密码',
border: OutlineInputBorder(),
),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消'),
),
TextButton(
onPressed: () async {
if (passwordController.text.isEmpty) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('密码不能为空')));
return;
}
if (!_isValidPassword(passwordController.text)) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('密码只能包含数字和字母')));
return;
}
if (passwordController.text != confirmPasswordController.text) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('两次密码不一致')));
return;
}
Navigator.of(context).pop();
await _setPassword(passwordController.text);
},
child: const Text('确定'),
),
],
),
);
}
// 显示设置密码对话框
Future<void> _showSetPasswordDialog() async {
final TextEditingController passwordController = TextEditingController();
final TextEditingController confirmPasswordController =
TextEditingController();
await showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('设置密码'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: '密码',
hintText: '只能输入数字和字母',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
TextField(
controller: confirmPasswordController,
obscureText: true,
decoration: const InputDecoration(
labelText: '确认密码',
hintText: '再次输入密码',
border: OutlineInputBorder(),
),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消'),
),
TextButton(
onPressed: () async {
if (passwordController.text.isEmpty) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('密码不能为空')));
return;
}
if (!_isValidPassword(passwordController.text)) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('密码只能包含数字和字母')));
return;
}
if (passwordController.text != confirmPasswordController.text) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('两次密码不一致')));
return;
}
Navigator.of(context).pop();
await _setPassword(passwordController.text);
},
child: const Text('确定'),
),
],
),
);
}
// 设置密码
Future<void> _setPassword(String password) async {
if (_currentNoteId == null) {
final title = _titleController.text.trim();
final content = _contentController.text.trim();
if (title.isEmpty && content.isEmpty) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('请先输入内容')));
return;
}
await _saveNote();
}
setState(() {
_isLocked = true;
_password = password;
});
await _saveNote();
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('密码设置成功,笔记已锁定')));
}
}
// 移除密码
Future<void> _removePassword() async {
if (_currentNoteId == null) return;
setState(() {
_isLocked = false;
_password = null;
});
await _saveNote();
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('已取消锁定')));
}
}
// 显示删除确认对话框
Future<void> _showDeleteDialog() async {
if (_currentNoteId == null) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('删除笔记'),
content: const Text('确定要删除这条笔记吗?此操作不可撤销。'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text('删除', style: TextStyle(color: Colors.red[400])),
),
],
),
);
if (confirmed == true) {
await HistoryController.deleteNote(_currentNoteId!);
NetworkListenerService().sendSuccessEvent(
NetworkEventType.noteUpdate,
data: _currentNoteId,
);
if (mounted) {
Navigator.of(context).pop();
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('笔记已删除')));
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: AppConstants.primaryColor),
onPressed: () => Navigator.of(context).pop(),
),
title: Text(
_currentNoteId == null ? '新建笔记' : '编辑笔记',
style: const TextStyle(
color: Colors.black87,
fontWeight: FontWeight.w600,
),
),
actions: [
// 删除按钮(仅编辑时显示)
if (_currentNoteId != null)
IconButton(
icon: Icon(Icons.delete_outline, color: Colors.red[400]),
onPressed: _showDeleteDialog,
tooltip: '删除笔记',
),
// 锁定按钮
IconButton(
icon: Icon(
_isLocked ? Icons.lock : Icons.lock_outline,
color: _isLocked ? AppConstants.primaryColor : Colors.grey[600],
),
onPressed: _showPasswordDialog,
tooltip: _isLocked ? '修改密码' : '设置密码',
),
// 置顶按钮
IconButton(
icon: Icon(
_isPinned ? Icons.push_pin : Icons.push_pin_outlined,
color: _isPinned ? AppConstants.primaryColor : Colors.grey[600],
),
onPressed: _togglePin,
tooltip: _isPinned ? '取消置顶' : '置顶',
),
],
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: GestureDetector(
onTap: () {
// 点击非输入框区域取消焦点
_titleFocusNode.unfocus();
_contentFocusNode.unfocus();
},
child: Column(
children: [
_buildStatusBar(),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
_buildTitleInput(),
const SizedBox(height: 16),
_buildContentInput(),
],
),
),
),
],
),
),
);
}
Widget _buildStatusBar() {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
color: Colors.grey[50],
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
// 创建时间
Icon(Icons.add_circle_outline, size: 14, color: Colors.grey[500]),
const SizedBox(width: 4),
Text(
_createTime != null ? '创建 ${_formatDate(_createTime!)}' : '新笔记',
style: TextStyle(fontSize: 12, color: Colors.grey[500]),
),
const SizedBox(width: 16),
// 保存时间
Icon(Icons.access_time, size: 14, color: Colors.grey[500]),
const SizedBox(width: 4),
Text(
_lastSavedTime != null
? '保存 ${_formatDateTime(_lastSavedTime!)}'
: '未保存',
style: TextStyle(fontSize: 12, color: Colors.grey[500]),
),
const SizedBox(width: 16),
// 字数
Icon(Icons.text_fields, size: 14, color: Colors.grey[500]),
const SizedBox(width: 4),
Text(
'$_charCount',
style: TextStyle(fontSize: 12, color: Colors.grey[500]),
),
if (_isPinned) ...[
const SizedBox(width: 16),
Icon(Icons.push_pin, size: 14, color: AppConstants.primaryColor),
const SizedBox(width: 4),
Text(
'已置顶',
style: TextStyle(
fontSize: 12,
color: AppConstants.primaryColor,
),
),
],
if (_isLocked) ...[
const SizedBox(width: 16),
Icon(Icons.lock, size: 14, color: AppConstants.primaryColor),
const SizedBox(width: 4),
Text(
'已锁定',
style: TextStyle(
fontSize: 12,
color: AppConstants.primaryColor,
),
),
],
],
),
),
);
}
// 显示自定义分类对话框
Future<void> _showCustomCategoryDialog() async {
final TextEditingController customCategoryController =
TextEditingController();
// 如果当前分类不在预设选项中,显示当前分类
if (_category != null &&
!_categoryOptions.contains(_category) &&
_category!.isNotEmpty) {
customCategoryController.text = _category!;
}
await showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('自定义分类'),
content: TextField(
controller: customCategoryController,
autofocus: true,
decoration: const InputDecoration(
labelText: '分类名称',
hintText: '输入自定义分类名称',
border: OutlineInputBorder(),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消'),
),
TextButton(
onPressed: () {
final customCategory = customCategoryController.text.trim();
if (customCategory.isEmpty) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('分类名称不能为空')));
return;
}
Navigator.of(context).pop();
setState(() {
_category = customCategory;
});
_saveNote();
},
child: const Text('确定'),
),
],
),
);
}
Widget _buildTitleInput() {
return Row(
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: _titleFocusNode.hasFocus
? AppConstants.primaryColor.withValues(alpha: 0.5)
: Colors.grey.withValues(alpha: 0.2),
width: 1.5,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: TextField(
controller: _titleController,
focusNode: _titleFocusNode,
maxLines: 1,
decoration: InputDecoration(
hintText: '标题(可选)',
hintStyle: TextStyle(color: Colors.grey[400]),
border: InputBorder.none,
contentPadding: const EdgeInsets.all(16),
),
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
),
),
const SizedBox(width: 12),
// 分类选择
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: PopupMenuButton<String>(
initialValue:
(_category != null && _categoryOptions.contains(_category))
? _category
: null,
onSelected: (value) async {
if (value == _customCategoryKey) {
// 弹出自定义分类输入框
await _showCustomCategoryDialog();
} else {
setState(() {
_category = value;
});
_saveNote();
}
},
itemBuilder: (context) {
final items = _categoryOptions.map((category) {
return PopupMenuItem(
value: category,
child: Row(
children: [
if (category == _category)
Icon(
Icons.check,
size: 16,
color: AppConstants.primaryColor,
),
if (category == _category) const SizedBox(width: 8),
Text(category),
],
),
);
}).toList();
// 添加自定义分类选项
items.add(
PopupMenuItem(
value: _customCategoryKey,
child: Row(
children: [
if (!_categoryOptions.contains(_category) &&
_category != null &&
_category!.isNotEmpty)
Icon(
Icons.check,
size: 16,
color: AppConstants.primaryColor,
),
if (!_categoryOptions.contains(_category) &&
_category != null &&
_category!.isNotEmpty)
const SizedBox(width: 8),
Icon(Icons.edit, size: 16, color: Colors.grey[600]),
const SizedBox(width: 8),
Text('自定义', style: TextStyle(color: Colors.grey[600])),
],
),
),
);
return items;
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.folder_outlined,
size: 18,
color: AppConstants.primaryColor,
),
const SizedBox(width: 4),
Text(
_category ?? '分类',
style: TextStyle(
fontSize: 14,
color: AppConstants.primaryColor,
),
),
Icon(
Icons.arrow_drop_down,
size: 18,
color: Colors.grey[600],
),
],
),
),
),
),
],
);
}
Widget _buildContentInput() {
return Container(
constraints: const BoxConstraints(minHeight: 300),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: _contentFocusNode.hasFocus
? AppConstants.primaryColor.withValues(alpha: 0.5)
: Colors.grey.withValues(alpha: 0.2),
width: 1.5,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 10,
offset: const Offset(0, 2),
),
],
),
child: TextField(
controller: _contentController,
focusNode: _contentFocusNode,
maxLines: null,
minLines: 12,
decoration: InputDecoration(
hintText: '开始写笔记...',
hintStyle: TextStyle(color: Colors.grey[400]),
border: InputBorder.none,
contentPadding: const EdgeInsets.all(16),
),
style: const TextStyle(fontSize: 16, height: 1.5),
),
);
}
String _formatDate(DateTime dateTime) {
return '${dateTime.month}-${dateTime.day}';
}
String _formatDateTime(DateTime dateTime) {
final now = DateTime.now();
final difference = now.difference(dateTime);
if (difference.inSeconds < 10) {
return '刚刚';
} else if (difference.inMinutes < 1) {
return '${difference.inSeconds}秒前';
} else if (difference.inMinutes < 60) {
return '${difference.inMinutes}分钟前';
} else if (difference.inHours < 24) {
return '${difference.inHours}小时前';
} else {
return '${dateTime.month}-${dateTime.day} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
}
}
}

View File

@@ -0,0 +1,692 @@
/// 时间: 2025-03-22
/// 功能: 点赞足迹页面
/// 介绍: 显示用户点赞的诗词列表,支持删除操作
/// 最新变化: 新增点赞足迹管理功能
import 'dart:async' show StreamSubscription;
import 'package:flutter/material.dart';
import 'package:flutter_application_2/controllers/history_controller.dart';
import '../../../constants/app_constants.dart';
import '../../../utils/http/poetry_api.dart';
import '../../../services/network_listener_service.dart';
import '../home/home_components.dart';
import '../home/home_part.dart';
/// 点赞足迹页面
class FootprintPage extends StatefulWidget {
const FootprintPage({super.key});
@override
State<FootprintPage> createState() => _FootprintPageState();
}
class _FootprintPageState extends State<FootprintPage>
with NetworkListenerMixin {
List<PoetryData> _likedPoetryList = [];
bool _isLoading = false;
String _errorMessage = '';
StreamSubscription<NetworkEvent>? _networkSubscription;
@override
void initState() {
super.initState();
_loadLikedPoetry();
_setupNetworkListener();
}
void _setupNetworkListener() {
// 监听网络事件
_networkSubscription = networkEvents.listen((event) {
if (mounted) {
switch (event.type) {
case NetworkEventType.like:
case NetworkEventType.unlike:
// 当有点赞或取消点赞事件时,刷新列表
_loadLikedPoetry();
break;
case NetworkEventType.refresh:
// 刷新事件
_loadLikedPoetry();
break;
default:
break;
}
}
});
}
@override
void dispose() {
_networkSubscription?.cancel();
super.dispose();
}
Future<void> _loadLikedPoetry() async {
setState(() {
_isLoading = true;
_errorMessage = '';
});
try {
// 从SQLite加载点赞列表
final likedListJson = await HistoryController.getLikedHistory();
final likedList = likedListJson
.map((item) => PoetryData.fromJson(item))
.toList();
if (mounted) {
setState(() {
_likedPoetryList = likedList;
_isLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_errorMessage = '加载点赞列表失败';
_isLoading = false;
});
}
}
}
Future<void> _showPoetryDetails(PoetryData poetry) async {
try {
print('DEBUG: 点击查看详情 - Poetry ID: ${poetry.id}');
// 从SQLite获取完整数据
final likedList = await HistoryController.getLikedHistory();
print('DEBUG: 获取到 ${likedList.length} 条点赞记录');
// 查找对应的诗词数据,优先使用存储的完整数据
Map<String, dynamic> poetryData;
try {
poetryData = likedList.firstWhere(
(item) => item['id'].toString() == poetry.id.toString(),
orElse: () => poetry.toJson(),
);
print('DEBUG: 找到匹配的诗词数据');
} catch (e) {
print('DEBUG: 未找到匹配数据使用当前poetry数据');
poetryData = poetry.toJson();
}
print('DEBUG: 诗词数据字段: ${poetryData.keys.toList()}');
if (mounted) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => Container(
height: MediaQuery.of(context).size.height * 0.8,
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Column(
children: [
// 顶部拖拽指示器
Container(
margin: const EdgeInsets.only(top: 8),
width: 40,
height: 4,
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(2),
),
),
// 标题栏
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(
Icons.article,
color: AppConstants.primaryColor,
size: 24,
),
const SizedBox(width: 8),
const Text(
'诗词详情',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
// 加载图标(不可点击)
GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('开发中'),
duration: Duration(seconds: 1),
),
);
},
child: Container(
padding: const EdgeInsets.all(8),
child: Icon(
Icons.more_horiz,
color: Colors.grey[600],
size: 20,
),
),
),
const SizedBox(width: 8),
// 关闭按钮
IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close),
color: Colors.grey[600],
),
],
),
),
// 内容区域
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 诗词名称 - 单独一行
_buildDetailCard(
'精选诗句',
poetryData['name'] ?? poetry.name,
Icons.format_quote,
AppConstants.primaryColor,
),
// 时间和标签 - 同一行
Row(
children: [
// 点赞时间
if (poetryData['liked_time'] != null) ...[
Expanded(
child: _buildDetailCard(
'点赞时间',
'${poetryData['liked_date'] ?? ''} ${poetryData['liked_time'] ?? ''}',
Icons.favorite,
Colors.orange,
),
),
],
// 标签
if (poetryData['keywords'] != null &&
poetryData['keywords']
.toString()
.isNotEmpty) ...[
const SizedBox(width: 8),
Expanded(
child: _buildDetailCard(
'标签',
poetryData['keywords'],
Icons.local_offer,
Colors.green,
),
),
],
],
),
// 朝代和出处 - 同一行
Row(
children: [
// 朝代
if (poetryData['alias'] != null &&
poetryData['alias'].toString().isNotEmpty) ...[
Expanded(
child: _buildDetailCard(
'朝代',
poetryData['alias'],
Icons.history,
Colors.blue,
),
),
],
// 出处
if (poetryData['url'] != null &&
poetryData['url'].toString().isNotEmpty) ...[
const SizedBox(width: 8),
Expanded(
child: _buildDetailCard(
'出处',
poetryData['url'],
Icons.link,
Colors.teal,
),
),
],
],
),
// 译文/介绍 - 单独一行
if (poetryData['introduce'] != null &&
poetryData['introduce'].toString().isNotEmpty)
_buildDetailCard(
'译文/介绍',
poetryData['introduce'],
Icons.translate,
AppConstants.primaryColor,
),
// 原文 - 单独一行
if (poetryData['drtime'] != null &&
poetryData['drtime'].toString().isNotEmpty)
_buildDetailCard(
'原文',
poetryData['drtime'],
Icons.menu_book,
Colors.purple,
),
const SizedBox(height: 20),
],
),
),
),
],
),
),
);
}
} catch (e) {
print('DEBUG: 显示详情失败 - $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('加载详情失败: $e'),
backgroundColor: AppConstants.errorColor,
duration: const Duration(seconds: 2),
),
);
}
}
}
Widget _buildDetailCard(
String title,
String content,
IconData icon,
Color accentColor,
) {
return Container(
width: double.infinity,
margin: const EdgeInsets.only(bottom: 12),
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.05),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: accentColor.withValues(alpha: 0.2), width: 1),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 标题栏
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.1),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
),
child: Row(
children: [
Icon(icon, size: 18, color: accentColor),
const SizedBox(width: 8),
Text(
title,
style: TextStyle(
fontSize: 14,
color: accentColor,
fontWeight: FontWeight.w600,
),
),
],
),
),
// 内容区域
Padding(
padding: const EdgeInsets.all(12),
child: Text(
content,
style: const TextStyle(
fontSize: 15,
color: Colors.black87,
height: 1.5,
),
),
),
],
),
);
}
Future<void> _removeLikedPoetry(String poetryId) async {
try {
// 从SQLite中删除
await HistoryController.removeLikedPoetry(poetryId);
// 重新加载列表
await _loadLikedPoetry();
if (mounted) {
PoetryStateManager.showSnackBar(
context,
'已取消点赞',
backgroundColor: AppConstants.successColor,
duration: const Duration(milliseconds: 200),
);
}
} catch (e) {
if (mounted) {
PoetryStateManager.showSnackBar(
context,
'操作失败,请重试',
backgroundColor: AppConstants.errorColor,
duration: const Duration(milliseconds: 200),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[50],
appBar: AppBar(
title: const Text('点赞足迹'),
backgroundColor: AppConstants.primaryColor,
foregroundColor: Colors.white,
elevation: 0,
),
body: _buildBody(),
);
}
Widget _buildBody() {
if (_isLoading) {
return const Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(AppConstants.primaryColor),
),
);
}
if (_errorMessage.isNotEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 64, color: AppConstants.errorColor),
const SizedBox(height: 16),
Text(
_errorMessage,
style: TextStyle(fontSize: 16, color: AppConstants.errorColor),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadLikedPoetry,
style: ElevatedButton.styleFrom(
backgroundColor: AppConstants.primaryColor,
foregroundColor: Colors.white,
),
child: const Text('重试'),
),
],
),
);
}
if (_likedPoetryList.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.favorite_border, size: 64, color: Colors.grey[400]),
const SizedBox(height: 16),
Text(
'暂无点赞记录',
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
const SizedBox(height: 8),
Text(
'去主页点赞喜欢的诗词吧',
style: TextStyle(fontSize: 14, color: Colors.grey[500]),
),
],
),
);
}
return RefreshIndicator(
onRefresh: _loadLikedPoetry,
child: Column(
children: [
// 添加不可点击的刷新按钮
if (_likedPoetryList.isNotEmpty) ...[
Container(
margin: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: Row(
children: [
Icon(
Icons.refresh,
size: 20,
color: AppConstants.primaryColor,
),
const SizedBox(width: 8),
Text(
'下拉刷新列表',
style: TextStyle(
fontSize: 14,
color: AppConstants.primaryColor,
fontWeight: FontWeight.w500,
),
),
const Spacer(),
Text(
'${_likedPoetryList.length} 条记录',
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
],
),
),
],
Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: _likedPoetryList.length,
itemBuilder: (context, index) {
final poetry = _likedPoetryList[index];
return _buildLikedPoetryCard(poetry);
},
),
),
],
),
);
}
Widget _buildLikedPoetryCard(PoetryData poetry) {
return Container(
margin: const EdgeInsets.only(bottom: 16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// URL字段 (出处)
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Text(
"出处: ${poetry.url}",
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.normal,
color: Colors.black,
fontStyle: FontStyle.italic,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
// Name字段 (精选诗句) - 与主页样式一致
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
margin: const EdgeInsets.symmetric(horizontal: 16),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppConstants.primaryColor.withValues(alpha: 0.1),
AppConstants.primaryColor.withValues(alpha: 0.05),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: AppConstants.primaryColor.withValues(alpha: 0.2),
width: 1,
),
boxShadow: [
BoxShadow(
color: AppConstants.primaryColor.withValues(alpha: 0.1),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.format_quote,
color: AppConstants.primaryColor,
size: 20,
),
const SizedBox(width: 8),
Expanded(
child: Text(
'精选诗句',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: AppConstants.primaryColor,
),
),
),
],
),
const SizedBox(height: 8),
Text(
poetry.name,
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold,
color: Colors.black87,
height: 1.4,
),
textAlign: TextAlign.center,
),
],
),
),
// drtime字段 (原文)
if (poetry.drtime.isNotEmpty) ...[
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFFF8F8F8),
borderRadius: BorderRadius.circular(8),
),
child: Text(
poetry.drtime,
style: const TextStyle(
fontSize: 14,
height: 1.6,
color: Colors.black87,
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
),
],
// 操作按钮
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: () => _removeLikedPoetry(poetry.id.toString()),
icon: const Icon(Icons.favorite_border, size: 18),
label: const Text('取消点赞'),
style: OutlinedButton.styleFrom(
foregroundColor: AppConstants.errorColor,
side: BorderSide(color: AppConstants.errorColor),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
),
const SizedBox(width: 12),
Expanded(
child: ElevatedButton.icon(
onPressed: () {
print('DEBUG: 查看详情按钮被点击 - Poetry ID: ${poetry.id}');
_showPoetryDetails(poetry);
},
icon: const Icon(Icons.visibility, size: 18),
label: const Text('查看详情'),
style: ElevatedButton.styleFrom(
backgroundColor: AppConstants.primaryColor,
foregroundColor: Colors.white,
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
padding: const EdgeInsets.symmetric(vertical: 12),
),
),
),
],
),
),
],
),
);
}
}

View File

@@ -0,0 +1,627 @@
/// 时间: 2025-03-22
/// 功能: 点赞诗词管理器
/// 介绍: 管理点赞诗词的加载、显示、删除等操作
/// 最新变化: 从FavoritesPage分离出来的点赞管理逻辑
library liked_poetry_manager;
import 'dart:async' show StreamSubscription;
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import '../../../constants/app_constants.dart';
import '../../../controllers/history_controller.dart';
import '../../../utils/http/poetry_api.dart';
import '../../../services/network_listener_service.dart';
import '../home/home_components.dart';
/// 点赞诗词管理器
class LikedPoetryManager extends StatefulWidget {
const LikedPoetryManager({super.key});
@override
State<LikedPoetryManager> createState() => _LikedPoetryManagerState();
/// 公共方法:显示诗词详情弹窗
/// 可被其他页面调用,无需传递额外参数
static Future<void> showPoetryDetails(
BuildContext context,
PoetryData poetry,
) async {
try {
debugPrint(
'DEBUG: LikedPoetryManager - 点击查看详情 - Poetry ID: ${poetry.id}',
);
final likedList = await HistoryController.getLikedHistory();
debugPrint('DEBUG: LikedPoetryManager - 获取到 ${likedList.length} 条点赞记录');
Map<String, dynamic> poetryData;
try {
poetryData = likedList.firstWhere(
(item) => item['id'].toString() == poetry.id.toString(),
orElse: () => poetry.toJson(),
);
debugPrint('DEBUG: LikedPoetryManager - 找到匹配的诗词数据');
} catch (e) {
debugPrint('DEBUG: LikedPoetryManager - 未找到匹配数据使用当前poetry数据');
poetryData = poetry.toJson();
}
debugPrint(
'DEBUG: LikedPoetryManager - 诗词数据字段: ${poetryData.keys.toList()}',
);
if (context.mounted) {
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => Container(
height: MediaQuery.of(context).size.height * 0.8,
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
child: Column(
children: [
Container(
margin: const EdgeInsets.only(top: 8),
width: 40,
height: 4,
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.circular(2),
),
),
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(
Icons.article,
color: AppConstants.primaryColor,
size: 24,
),
const SizedBox(width: 8),
const Text(
'诗词详情',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('开发中'),
duration: Duration(seconds: 1),
),
);
},
child: Container(
padding: const EdgeInsets.all(8),
child: Icon(
Icons.refresh,
color: Colors.grey[600],
size: 20,
),
),
),
const SizedBox(width: 8),
IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close),
color: Colors.grey[600],
),
],
),
),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildDetailCard(
'精选诗句',
poetryData['name'] ?? poetry.name,
Icons.format_quote,
AppConstants.primaryColor,
),
Row(
children: [
if (poetryData['liked_time'] != null) ...[
Expanded(
child: _buildDetailCard(
'点赞时间',
'${poetryData['liked_date'] ?? ''} ${poetryData['liked_time'] ?? ''}',
Icons.favorite,
Colors.orange,
),
),
],
if (poetryData['keywords'] != null &&
poetryData['keywords']
.toString()
.isNotEmpty) ...[
const SizedBox(width: 8),
Expanded(
child: _buildDetailCard(
'标签',
poetryData['keywords'],
Icons.local_offer,
Colors.green,
),
),
],
],
),
Row(
children: [
if (poetryData['alias'] != null &&
poetryData['alias'].toString().isNotEmpty) ...[
Expanded(
child: _buildDetailCard(
'出处',
poetryData['url'],
Icons.link,
Colors.teal,
),
),
],
if (poetryData['url'] != null &&
poetryData['url'].toString().isNotEmpty) ...[
const SizedBox(width: 8),
Expanded(
child: _buildDetailCard(
'朝代',
poetryData['alias'],
Icons.history,
Colors.blue,
),
),
],
],
),
if (poetryData['introduce'] != null &&
poetryData['introduce'].toString().isNotEmpty)
_buildDetailCard(
'译文/介绍',
poetryData['introduce'],
Icons.translate,
AppConstants.primaryColor,
),
if (poetryData['drtime'] != null &&
poetryData['drtime'].toString().isNotEmpty)
_buildDetailCard(
'原文or赏析',
poetryData['drtime'],
Icons.menu_book,
Colors.purple,
),
const SizedBox(height: 20),
],
),
),
),
],
),
),
);
}
} catch (e) {
debugPrint('DEBUG: LikedPoetryManager - 显示详情失败 - $e');
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('加载详情失败: $e'),
backgroundColor: AppConstants.errorColor,
duration: const Duration(seconds: 2),
),
);
}
}
}
/// 公共方法:构建详情卡片
static Widget _buildDetailCard(
String title,
String content,
IconData icon,
Color accentColor,
) {
return Container(
width: double.infinity,
margin: const EdgeInsets.only(bottom: 12),
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.05),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: accentColor.withValues(alpha: 0.2), width: 1),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.1),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
),
child: Row(
children: [
Icon(icon, size: 18, color: accentColor),
const SizedBox(width: 8),
Text(
title,
style: TextStyle(
fontSize: 14,
color: accentColor,
fontWeight: FontWeight.w600,
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(12),
child: Text(
content,
style: const TextStyle(
fontSize: 15,
color: Colors.black87,
height: 1.5,
),
),
),
],
),
);
}
}
class _LikedPoetryManagerState extends State<LikedPoetryManager>
with NetworkListenerMixin {
List<PoetryData> _likedPoetryList = [];
bool _isLoading = false;
String _errorMessage = '';
StreamSubscription<NetworkEvent>? _networkSubscription;
@override
void initState() {
super.initState();
_loadLikedPoetry();
_setupNetworkListener();
}
void _setupNetworkListener() {
// 监听网络事件
_networkSubscription = networkEvents.listen((event) {
if (mounted) {
switch (event.type) {
case NetworkEventType.like:
case NetworkEventType.unlike:
// 当有点赞或取消点赞事件时,刷新列表
_loadLikedPoetry();
break;
case NetworkEventType.refresh:
// 刷新事件
_loadLikedPoetry();
break;
default:
break;
}
}
});
}
@override
void dispose() {
_networkSubscription?.cancel();
super.dispose();
}
Future<void> _loadLikedPoetry() async {
setState(() {
_isLoading = true;
_errorMessage = '';
});
try {
// 从SQLite加载点赞列表
final likedListJson = await HistoryController.getLikedHistory();
final likedList = likedListJson
.map((item) => PoetryData.fromJson(item))
.toList();
if (mounted) {
setState(() {
_likedPoetryList = likedList;
_isLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_errorMessage = '加载点赞列表失败';
_isLoading = false;
});
}
}
}
Future<void> _showPoetryDetails(PoetryData poetry) async {
await LikedPoetryManager.showPoetryDetails(context, poetry);
}
Future<void> _removeLikedPoetry(String poetryId) async {
try {
// 从SQLite中删除
await HistoryController.removeLikedPoetry(poetryId);
// 重新加载列表
await _loadLikedPoetry();
if (mounted) {
PoetryStateManager.showSnackBar(
context,
'已取消点赞',
backgroundColor: AppConstants.successColor,
duration: const Duration(milliseconds: 200),
);
}
} catch (e) {
if (mounted) {
PoetryStateManager.showSnackBar(
context,
'操作失败,请重试',
backgroundColor: AppConstants.errorColor,
duration: const Duration(milliseconds: 200),
);
}
}
}
@override
Widget build(BuildContext context) {
return _buildLikedPoetryList();
}
Widget _buildLikedPoetryList() {
if (_isLoading) {
return const Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(AppConstants.primaryColor),
),
);
}
if (_errorMessage.isNotEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 64, color: AppConstants.errorColor),
const SizedBox(height: 16),
Text(
_errorMessage,
style: TextStyle(fontSize: 16, color: AppConstants.errorColor),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadLikedPoetry,
style: ElevatedButton.styleFrom(
backgroundColor: AppConstants.primaryColor,
foregroundColor: Colors.white,
),
child: const Text('重试'),
),
],
),
);
}
if (_likedPoetryList.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.favorite_border, size: 64, color: Colors.grey[400]),
const SizedBox(height: 16),
Text(
'暂无点赞记录',
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
const SizedBox(height: 8),
Text(
'去主页点赞喜欢的诗词吧',
style: TextStyle(fontSize: 14, color: Colors.grey[500]),
),
],
),
);
}
return RefreshIndicator(
onRefresh: _loadLikedPoetry,
child: ListView.builder(
padding: const EdgeInsets.all(16),
itemCount: _likedPoetryList.length + 1,
itemBuilder: (context, index) {
if (index == _likedPoetryList.length) {
return _buildBottomIndicator();
}
final poetry = _likedPoetryList[index];
return _buildLikedPoetryCard(poetry);
},
),
);
}
Widget _buildBottomIndicator() {
return Container(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(width: 40, height: 1, color: Colors.grey[300]),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'到底了',
style: TextStyle(fontSize: 12, color: Colors.grey[400]),
),
),
Container(width: 40, height: 1, color: Colors.grey[300]),
],
),
);
}
Widget _buildLikedPoetryCard(PoetryData poetry) {
return Container(
margin: const EdgeInsets.only(bottom: 8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.03),
blurRadius: 4,
offset: const Offset(0, 1),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Name字段 (精选诗句) - 超紧凑样式
Container(
width: double.infinity,
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppConstants.primaryColor.withValues(alpha: 0.1),
AppConstants.primaryColor.withValues(alpha: 0.05),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(6),
border: Border.all(
color: AppConstants.primaryColor.withValues(alpha: 0.2),
width: 1,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Icon(
Icons.format_quote,
color: AppConstants.primaryColor,
size: 14,
),
const SizedBox(width: 4),
Text(
'精选诗句',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w500,
color: AppConstants.primaryColor,
),
),
],
),
const SizedBox(height: 4),
Text(
poetry.name,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.black87,
height: 1.2,
),
),
],
),
),
// URL字段 (出处) - 超紧凑样式
if (poetry.url.isNotEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 8, 2),
child: Text(
"出处:${poetry.url}",
style: TextStyle(fontSize: 11, color: Colors.grey[600]),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
// 操作按钮 - 超紧凑样式
Padding(
padding: const EdgeInsets.fromLTRB(8, 2, 8, 8),
child: Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: () => _removeLikedPoetry(poetry.id.toString()),
icon: const Icon(Icons.favorite_border, size: 14),
label: const Text('取消点赞', style: TextStyle(fontSize: 12)),
style: OutlinedButton.styleFrom(
foregroundColor: AppConstants.errorColor,
side: BorderSide(color: AppConstants.errorColor),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
padding: const EdgeInsets.symmetric(vertical: 4),
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
),
),
const SizedBox(width: 6),
Expanded(
child: ElevatedButton.icon(
onPressed: () {
debugPrint(
'DEBUG: LikedPoetryManager - 查看详情按钮被点击 - Poetry ID: ${poetry.id}',
);
_showPoetryDetails(poetry);
},
icon: const Icon(Icons.visibility, size: 14),
label: const Text('查看详情', style: TextStyle(fontSize: 12)),
style: ElevatedButton.styleFrom(
backgroundColor: AppConstants.primaryColor,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
padding: const EdgeInsets.symmetric(vertical: 4),
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
),
),
],
),
),
],
),
);
}
}

View File

@@ -0,0 +1,620 @@
import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import '../../constants/app_constants.dart';
import 'collect_notes.dart';
import '../../controllers/history_controller.dart';
import '../../services/network_listener_service.dart';
/// 时间: 2026-03-26
/// 功能: 本地笔记列表组件
/// 介绍: 展示用户笔记列表,支持置顶、锁定、删除等功能
/// 最新变化: 从 favorites_page.dart 独立出来,支持实时更新
class LocalNotesList extends StatefulWidget {
const LocalNotesList({super.key});
@override
State<LocalNotesList> createState() => _LocalNotesListState();
}
class _LocalNotesListState extends State<LocalNotesList> {
List<Map<String, dynamic>> _notes = [];
bool _isLoadingNotes = false;
StreamSubscription<NetworkEvent>? _networkSubscription;
@override
void initState() {
super.initState();
_loadNotes();
_listenToNoteUpdates();
}
@override
void dispose() {
_networkSubscription?.cancel();
super.dispose();
}
void _listenToNoteUpdates() {
_networkSubscription = NetworkListenerService().eventStream.listen((event) {
if (event.type == NetworkEventType.noteUpdate) {
_loadNotes();
}
});
}
// 加载笔记列表
Future<void> _loadNotes() async {
if (_isLoadingNotes) return;
setState(() {
_isLoadingNotes = true;
});
try {
final notes = await HistoryController.getNotes();
if (mounted) {
setState(() {
_notes = notes;
_isLoadingNotes = false;
});
}
} catch (e) {
print('加载笔记失败: $e');
if (mounted) {
setState(() {
_isLoadingNotes = false;
});
}
}
}
@override
Widget build(BuildContext context) {
if (_isLoadingNotes && _notes.isEmpty) {
return const Center(child: CircularProgressIndicator());
}
if (_notes.isEmpty) {
return _buildEmptyNotes();
}
return RefreshIndicator(
onRefresh: _loadNotes,
child: ListView.builder(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 80),
itemCount: _notes.length + 1,
itemBuilder: (context, index) {
if (index == _notes.length) {
return _buildBottomIndicator();
}
final note = _notes[index];
return _buildNoteCard(note);
},
),
);
}
Widget _buildBottomIndicator() {
return Container(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(width: 40, height: 1, color: Colors.grey[300]),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'到底了',
style: TextStyle(fontSize: 12, color: Colors.grey[400]),
),
),
Container(width: 40, height: 1, color: Colors.grey[300]),
],
),
);
}
// 构建空笔记状态
Widget _buildEmptyNotes() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.note_add_outlined, size: 64, color: Colors.grey[400]),
const SizedBox(height: 16),
Text('暂无笔记', style: TextStyle(fontSize: 16, color: Colors.grey[600])),
const SizedBox(height: 8),
Text(
'点击右下角按钮创建新笔记',
style: TextStyle(fontSize: 14, color: Colors.grey[500]),
),
],
),
);
}
// 构建笔记卡片
Widget _buildNoteCard(Map<String, dynamic> note) {
final title = note['title'] as String? ?? '';
final content = note['content'] as String? ?? '';
final timeStr = note['time'] as String? ?? '';
final createTimeStr = note['createTime'] as String? ?? '';
final category = note['category'] as String? ?? '';
final isPinned = note['isPinned'] == true;
final isLocked = note['isLocked'] == true;
// 显示逻辑:有标题显示标题,无标题有分类显示分类,否则显示内容
String displayText;
bool hasTitle = title.isNotEmpty;
bool hasCategory = category.isNotEmpty && category != '未分类';
if (hasTitle) {
displayText = title;
} else if (hasCategory) {
displayText = '[$category]';
} else {
displayText = content;
}
return Container(
margin: const EdgeInsets.only(bottom: 16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.08),
blurRadius: 12,
offset: const Offset(0, 4),
),
BoxShadow(
color: Colors.black.withValues(alpha: 0.04),
blurRadius: 6,
offset: const Offset(0, 2),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Stack(
children: [
// 原始内容
InkWell(
onTap: () => _handleNoteTap(note, isLocked),
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 顶部:创建时间、保存时间和置顶/锁定按钮
Row(
children: [
// 创建时间
if (createTimeStr.isNotEmpty) ...[
Icon(
Icons.add_circle_outline,
size: 12,
color: Colors.grey[400],
),
const SizedBox(width: 2),
Text(
_formatDate(createTimeStr),
style: TextStyle(
fontSize: 10,
color: Colors.grey[400],
),
),
const SizedBox(width: 8),
],
// 保存时间
Icon(
Icons.access_time,
size: 12,
color: Colors.grey[400],
),
const SizedBox(width: 2),
Text(
_formatDateTime(timeStr),
style: TextStyle(
fontSize: 10,
color: Colors.grey[400],
),
),
const Spacer(),
// 分类标签
if (hasCategory)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 2,
),
decoration: BoxDecoration(
color: AppConstants.primaryColor.withValues(
alpha: 0.1,
),
borderRadius: BorderRadius.circular(10),
),
child: Text(
category,
style: TextStyle(
fontSize: 10,
color: AppConstants.primaryColor,
),
),
),
if (hasCategory) const SizedBox(width: 8),
// 锁定图标
if (isLocked)
Container(
padding: const EdgeInsets.all(4),
child: Icon(
Icons.lock,
size: 16,
color: AppConstants.primaryColor,
),
),
// 置顶按钮
GestureDetector(
onTap: () => _togglePin(note['id'] as String?),
child: Container(
padding: const EdgeInsets.all(4),
child: Icon(
isPinned
? Icons.push_pin
: Icons.push_pin_outlined,
size: 16,
color: isPinned
? AppConstants.primaryColor
: Colors.grey[400],
),
),
),
],
),
const SizedBox(height: 12),
// 标题或内容
Text(
displayText,
style: TextStyle(
fontSize: hasTitle ? 16 : 14,
fontWeight: hasTitle
? FontWeight.w600
: FontWeight.normal,
color: Colors.black87,
height: 1.5,
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
// 底部:字数和删除按钮
const SizedBox(height: 12),
Row(
children: [
Text(
'${note['charCount'] ?? displayText.length}',
style: TextStyle(
fontSize: 12,
color: Colors.grey[400],
),
),
const Spacer(),
// 删除按钮
GestureDetector(
onTap: () =>
_showDeleteNoteDialog(note['id'] as String?),
child: Container(
padding: const EdgeInsets.all(4),
child: Icon(
Icons.delete_outline,
size: 18,
color: Colors.grey[400],
),
),
),
],
),
],
),
),
),
// 锁定时的毛玻璃遮罩
if (isLocked)
Positioned.fill(
child: GestureDetector(
onTap: () => _handleNoteTap(note, isLocked),
child: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 8, sigmaY: 8),
child: Container(
color: Colors.white.withValues(alpha: 0.3),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
// 顶部时间信息
Row(
children: [
Icon(
Icons.access_time,
size: 12,
color: Colors.grey[600],
),
const SizedBox(width: 4),
Text(
_formatDateTime(timeStr),
style: TextStyle(
fontSize: 10,
color: Colors.grey[600],
),
),
const Spacer(),
// 删除按钮
GestureDetector(
onTap: () => _showDeleteNoteDialog(
note['id'] as String?,
),
child: Container(
padding: const EdgeInsets.all(4),
child: Icon(
Icons.delete_outline,
size: 16,
color: Colors.grey[600],
),
),
),
],
),
const Spacer(),
// 中间锁定图标(左右结构)
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.lock,
size: 28,
color: AppConstants.primaryColor,
),
const SizedBox(width: 12),
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
'已锁定',
style: TextStyle(
fontSize: 14,
color: AppConstants.primaryColor,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 2),
Text(
'点击输入密码访问',
style: TextStyle(
fontSize: 12,
color: Colors.grey[600],
),
),
],
),
],
),
const Spacer(),
// 底部字数
Row(
children: [
Text(
'${note['charCount'] ?? displayText.length}',
style: TextStyle(
fontSize: 10,
color: Colors.grey[600],
),
),
],
),
],
),
),
),
),
),
),
),
],
),
),
);
}
// 处理笔记点击
Future<void> _handleNoteTap(Map<String, dynamic> note, bool isLocked) async {
final noteId = note['id'] as String?;
if (noteId == null) return;
if (isLocked) {
// 显示密码输入对话框
final password = await _showPasswordInputDialog(noteId);
if (password == null) return;
// 验证密码
final isValid = await HistoryController.verifyNotePassword(
noteId,
password,
);
if (!isValid) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('密码错误')));
}
return;
}
}
// 进入编辑页面
if (mounted) {
Navigator.of(context)
.push(
MaterialPageRoute<void>(
builder: (_) => CollectNotesPage(noteId: noteId),
),
)
.then((_) {
_loadNotes();
});
}
}
// 显示密码输入对话框
Future<String?> _showPasswordInputDialog(String noteId) async {
final TextEditingController passwordController = TextEditingController();
return showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: const Row(
children: [
Icon(Icons.lock, size: 20),
SizedBox(width: 8),
Text('输入密码'),
],
),
content: TextField(
controller: passwordController,
obscureText: true,
autofocus: true,
decoration: const InputDecoration(
hintText: '请输入访问密码',
border: OutlineInputBorder(),
),
onSubmitted: (value) {
Navigator.of(context).pop(value);
},
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(null),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.of(context).pop(passwordController.text),
child: const Text('确定'),
),
],
),
);
}
// 切换置顶状态
Future<void> _togglePin(String? noteId) async {
if (noteId == null) return;
try {
await HistoryController.togglePinNote(noteId);
NetworkListenerService().sendSuccessEvent(
NetworkEventType.noteUpdate,
data: noteId,
);
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('已更新置顶状态')));
}
} catch (e) {
print('切换置顶失败: $e');
}
}
// 格式化创建日期
String _formatDate(String timeStr) {
if (timeStr.isEmpty) return '';
try {
final dateTime = DateTime.parse(timeStr);
return '${dateTime.month}-${dateTime.day}';
} catch (e) {
return '';
}
}
// 格式化日期时间
String _formatDateTime(String timeStr) {
if (timeStr.isEmpty) return '';
try {
final dateTime = DateTime.parse(timeStr);
final now = DateTime.now();
final difference = now.difference(dateTime);
if (difference.inMinutes < 1) {
return '刚刚';
} else if (difference.inMinutes < 60) {
return '${difference.inMinutes}分钟前';
} else if (difference.inHours < 24) {
return '${difference.inHours}小时前';
} else if (difference.inDays < 7) {
return '${difference.inDays}天前';
} else if (difference.inDays < 30) {
return '${(difference.inDays / 7).floor()}周前';
} else {
return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}';
}
} catch (e) {
return timeStr;
}
}
// 显示删除笔记对话框
void _showDeleteNoteDialog(String? noteId) {
if (noteId == null) return;
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('确认删除'),
content: const Text('确定要删除这条笔记吗?'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('取消'),
),
TextButton(
onPressed: () async {
Navigator.of(context).pop();
await _deleteNote(noteId);
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
// 删除笔记
Future<void> _deleteNote(String noteId) async {
try {
await HistoryController.deleteNote(noteId);
NetworkListenerService().sendSuccessEvent(
NetworkEventType.noteUpdate,
data: noteId,
);
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('删除成功')));
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('删除失败: $e')));
}
}
}
}