结构重构

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,412 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:provider/provider.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../utils/toast_util.dart';
/// 笔记详情页 - 极简主义设计
class NoteDetailPage extends StatefulWidget {
final Note note;
const NoteDetailPage({super.key, required this.note});
@override
State<NoteDetailPage> createState() => _NoteDetailPageState();
}
class _NoteDetailPageState extends State<NoteDetailPage> {
@override
Widget build(BuildContext context) {
// 从 Provider 获取最新的笔记数据
final note = context.watch<AppProvider>().notes.firstWhere(
(n) => n.id == widget.note.id,
orElse: () => widget.note,
);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(_getTitle(note.content)),
actions: [
// 格式指示器 - 纯文本标记
if (note.contentType == 'markdown')
Container(
margin: const EdgeInsets.only(right: 8),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
borderRadius: BorderRadius.circular(2),
),
child: const Text(
'MD',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w500,
color: Color(0xFF666666),
),
),
)
else
Container(
margin: const EdgeInsets.only(right: 8),
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
borderRadius: BorderRadius.circular(2),
),
child: const Text(
'TXT',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w500,
color: Color(0xFF666666),
),
),
),
IconButton(
icon: const Icon(Icons.edit_outlined),
onPressed: () => _navigateToEdit(context),
),
const SizedBox(width: 8),
],
),
body: Column(
children: [
// 标签区域
if (note.tags.isNotEmpty)
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: [
Wrap(
spacing: 8,
runSpacing: 8,
children: note.tags.map((tag) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Text(
tag,
style: const TextStyle(
fontSize: 12,
color: Color(0xFF666666),
),
),
);
}).toList(),
),
],
),
),
// 内容区域
Expanded(
child: note.contentType == 'markdown'
? _buildMarkdownContent(note)
: _buildPlainTextContent(note),
),
// 图片区域(仅在纯文本模式下显示)
if (note.contentType == 'plain_text' && note.images.isNotEmpty)
Container(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 20),
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: Color(0xFFE5E5E5), width: 0.5),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 图片标题
Row(
children: [
const Icon(
Icons.image_outlined,
size: 14,
color: Color(0xFF999999),
),
const SizedBox(width: 6),
Text(
'图片 (${note.images.length})',
style: const TextStyle(
fontSize: 12,
color: Color(0xFF999999),
),
),
],
),
const SizedBox(height: 12),
// 图片列表
SizedBox(
height: 100,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: note.images.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () => _showImagePreview(context, note.images, index),
child: Container(
width: 100,
height: 100,
margin: const EdgeInsets.only(right: 12),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Image.file(
File(note.images[index]),
fit: BoxFit.cover,
),
),
);
},
),
),
],
),
),
// 底部操作栏
Container(
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: Color(0xFFE5E5E5), width: 0.5),
),
),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// 创建时间和更新时间
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'创建时间:${_formatDateTime(note.createdAt)}',
style: const TextStyle(
fontSize: 11,
color: Color(0xFF999999),
),
),
const SizedBox(height: 4),
Text(
'更新时间:${_formatDateTime(note.updatedAt)}',
style: const TextStyle(
fontSize: 11,
color: Color(0xFF999999),
),
),
],
),
),
Row(
children: [
IconButton(
icon: const Icon(Icons.edit_outlined, size: 20),
color: const Color(0xFF666666),
onPressed: () => _navigateToEdit(context),
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
const SizedBox(width: 16),
IconButton(
icon: const Icon(Icons.delete_outline, size: 20),
color: Colors.red,
onPressed: () => _showDeleteDialog(context),
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
],
),
],
),
],
),
),
),
),
],
),
);
}
/// 构建 Markdown 内容
Widget _buildMarkdownContent(Note note) {
return Markdown(
data: note.content,
styleSheet: MarkdownStyleSheet(
h1: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w600,
color: Color(0xFF1A1A1A),
height: 1.4,
),
h2: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Color(0xFF1A1A1A),
height: 1.4,
),
h3: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
color: Color(0xFF1A1A1A),
height: 1.4,
),
p: const TextStyle(
fontSize: 16,
color: Color(0xFF1A1A1A),
height: 1.8,
),
code: const TextStyle(
fontSize: 14,
color: Color(0xFF1A1A1A),
backgroundColor: Color(0xFFF5F5F5),
),
codeblockDecoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5)),
),
blockquote: const TextStyle(
fontSize: 16,
color: Color(0xFF666666),
fontStyle: FontStyle.italic,
),
blockquoteDecoration: BoxDecoration(
border: Border(
left: BorderSide(color: const Color(0xFF999999), width: 4),
),
),
listBullet: const TextStyle(
fontSize: 16,
color: Color(0xFF1A1A1A),
),
a: const TextStyle(
fontSize: 16,
color: Color(0xFF1A1A1A),
decoration: TextDecoration.underline,
),
),
padding: const EdgeInsets.all(16),
);
}
/// 构建纯文本内容
Widget _buildPlainTextContent(Note note) {
return SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: SizedBox(
width: double.infinity,
child: SelectableText(
note.content,
textAlign: TextAlign.left,
style: const TextStyle(
fontSize: 15,
color: Color(0xFF1A1A1A),
height: 1.9,
letterSpacing: 0.2,
),
),
),
);
}
/// 格式化日期时间
String _formatDateTime(DateTime dateTime) {
return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
}
/// 获取标题内容前5个字
String _getTitle(String content) {
if (content.isEmpty) return '无标题';
// 移除换行符和多余空格
final trimmed = content.replaceAll('\n', ' ').trim();
if (trimmed.isEmpty) return '无标题';
// 取前5个字
if (trimmed.length <= 5) return trimmed;
return '${trimmed.substring(0, 5)}...';
}
/// 跳转到编辑页面
void _navigateToEdit(BuildContext context) {
// 从 Provider 获取最新的笔记数据,确保图片等字段是最新的
final currentNote = context.read<AppProvider>().notes.firstWhere(
(n) => n.id == widget.note.id,
orElse: () => widget.note,
);
Navigator.pushNamed(context, '/note-form', arguments: currentNote).then((_) {
context.read<AppProvider>().loadNotes();
});
}
/// 显示图片预览
void _showImagePreview(BuildContext context, List<String> images, int initialIndex) {
showDialog(
context: context,
barrierDismissible: true,
builder: (context) => GestureDetector(
onTap: () => Navigator.pop(context),
child: Container(
color: Colors.black.withOpacity(0.9),
child: Center(
child: InteractiveViewer(
panEnabled: true,
boundaryMargin: const EdgeInsets.all(20),
minScale: 0.5,
maxScale: 4,
child: Image.file(
File(images[initialIndex]),
fit: BoxFit.contain,
),
),
),
),
),
);
}
/// 显示删除对话框
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: const Text('确定要删除这条笔记吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () async {
await context.read<AppProvider>().removeNote(widget.note.id);
if (!mounted) return;
Navigator.pop(context);
Navigator.pop(context);
ToastUtil.show(context, '已删除');
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
}

View File

@@ -0,0 +1,731 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as p;
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../utils/toast_util.dart';
import '../../utils/image_path_helper.dart';
/// 添加/编辑笔记页面 - 极简书写界面
class NoteFormPage extends StatefulWidget {
final Note? note;
const NoteFormPage({super.key, this.note});
@override
State<NoteFormPage> createState() => _NoteFormPageState();
}
class _NoteFormPageState extends State<NoteFormPage> {
late TextEditingController _contentController;
late DateTime _createdAt;
List<String> _tags = [];
List<String> _images = []; // 图片路径列表
String _contentType = 'markdown'; // markdown / plain_text
bool _isEditing = false;
final ImagePicker _picker = ImagePicker();
String? _tempNoteId; // 新建模式时使用的临时笔记ID
@override
void initState() {
super.initState();
final note = widget.note;
_contentController = TextEditingController(text: note?.content ?? '');
_createdAt = note?.createdAt ?? DateTime.now();
_tags = note != null ? List.from(note.tags) : [];
_images = note != null ? List.from(note.images) : [];
_contentType = note?.contentType ?? 'markdown';
_isEditing = note != null;
}
@override
void dispose() {
_contentController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text(_isEditing ? '编辑笔记' : '新建笔记'),
actions: [
TextButton(
onPressed: _saveNote,
child: const Text(
'保存',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
const SizedBox(width: 8),
],
),
body: Column(
children: [
// 顶部信息栏:创建时间 + 格式选择 + 标签
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(color: Color(0xFFE5E5E5), width: 0.5),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
// 创建时间
Text(
_formatDateTime(_createdAt),
style: const TextStyle(
fontSize: 12,
color: Color(0xFF999999),
),
),
const Spacer(),
// 格式选择
_buildFormatSelector(),
],
),
const SizedBox(height: 8),
// 标签
_buildTagSelector(),
],
),
),
// 书写区域纯文本模式下占据35%高度Markdown模式下占据全部
if (_contentType == 'plain_text')
SizedBox(
height: MediaQuery.of(context).size.height * 0.35,
child: TextField(
controller: _contentController,
maxLines: null,
expands: true,
textAlignVertical: TextAlignVertical.top,
style: const TextStyle(
fontSize: 16,
color: Color(0xFF1A1A1A),
height: 1.6,
),
decoration: const InputDecoration(
hintText: '开始书写...',
hintStyle: TextStyle(
fontSize: 16,
color: Color(0xFFCCCCCC),
),
border: InputBorder.none,
contentPadding: EdgeInsets.all(16),
),
),
)
else
Expanded(
child: TextField(
controller: _contentController,
maxLines: null,
expands: true,
textAlignVertical: TextAlignVertical.top,
style: const TextStyle(
fontSize: 16,
color: Color(0xFF1A1A1A),
height: 1.6,
),
decoration: const InputDecoration(
hintText: '使用 Markdown 格式书写...',
hintStyle: TextStyle(
fontSize: 16,
color: Color(0xFFCCCCCC),
),
border: InputBorder.none,
contentPadding: EdgeInsets.all(16),
),
),
),
// 纯文本模式下的图片区域
if (_contentType == 'plain_text') ...[
// 图片网格区域
Expanded(
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 标题栏
Row(
children: [
const Text(
'图片',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: Color(0xFF1A1A1A),
),
),
const SizedBox(width: 8),
Text(
'${_images.length}',
style: const TextStyle(
fontSize: 14,
color: Color(0xFF999999),
),
),
const Spacer(),
// 添加图片按钮
InkWell(
onTap: _pickImage,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFF1A1A1A),
borderRadius: BorderRadius.circular(2),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.add,
size: 16,
color: Colors.white,
),
SizedBox(width: 4),
Text(
'添加',
style: TextStyle(
fontSize: 12,
color: Colors.white,
),
),
],
),
),
),
],
),
const SizedBox(height: 12),
// 图片网格4列正方形铺满
Expanded(
child: _images.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.image_outlined,
size: 48,
color: const Color(0xFFCCCCCC),
),
const SizedBox(height: 8),
const Text(
'点击添加按钮添加图片',
style: TextStyle(
fontSize: 13,
color: Color(0xFF999999),
),
),
],
),
)
: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
childAspectRatio: 1.0,
),
itemCount: _images.length,
itemBuilder: (context, index) {
return _buildImageItem(index);
},
),
),
],
),
),
),
],
],
),
);
}
/// 构建格式选择器
Widget _buildFormatSelector() {
return GestureDetector(
onTap: () => _showFormatSelector(),
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: [
Icon(
_contentType == 'markdown' ? Icons.code : Icons.text_fields,
size: 14,
color: const Color(0xFF666666),
),
const SizedBox(width: 4),
Text(
_contentType == 'markdown' ? 'Markdown' : '纯文本',
style: const TextStyle(
fontSize: 12,
color: Color(0xFF666666),
),
),
const SizedBox(width: 4),
const Icon(
Icons.arrow_drop_down,
size: 16,
color: Color(0xFF999999),
),
],
),
),
);
}
/// 显示格式选择对话框
void _showFormatSelector() {
showModalBottomSheet(
context: context,
backgroundColor: Colors.white,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: const Icon(Icons.code, size: 20),
title: const Text('Markdown'),
subtitle: const Text('支持 Markdown 语法'),
trailing: _contentType == 'markdown'
? const Icon(Icons.check, color: Color(0xFF1A1A1A))
: null,
onTap: () {
setState(() => _contentType = 'markdown');
Navigator.pop(context);
},
),
const Divider(height: 0.5, indent: 56),
ListTile(
leading: const Icon(Icons.text_fields, size: 20),
title: const Text('纯文本'),
subtitle: const Text('普通文本格式,支持图片'),
trailing: _contentType == 'plain_text'
? const Icon(Icons.check, color: Color(0xFF1A1A1A))
: null,
onTap: () {
setState(() => _contentType = 'plain_text');
Navigator.pop(context);
},
),
],
),
),
);
}
/// 构建标签选择器
Widget _buildTagSelector() {
return Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
..._tags.asMap().entries.map((entry) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
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: 12,
color: Color(0xFF666666),
),
),
const SizedBox(width: 4),
GestureDetector(
onTap: () => setState(() => _tags.removeAt(entry.key)),
child: const Icon(
Icons.close,
size: 12,
color: Color(0xFF999999),
),
),
],
),
);
}),
// 添加标签按钮
GestureDetector(
onTap: () => _showAddTagDialog(),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.add,
size: 12,
color: Color(0xFF999999),
),
SizedBox(width: 2),
Text(
'标签',
style: TextStyle(
fontSize: 12,
color: Color(0xFF999999),
),
),
],
),
),
),
],
);
}
/// 显示添加标签对话框
void _showAddTagDialog() {
final controller = TextEditingController();
// 获取所有已有标签(从所有笔记中收集)
final provider = context.read<AppProvider>();
final allTags = _getAllExistingTags(provider);
// 过滤掉已添加的标签
final availableTags = allTags.where((tag) => !_tags.contains(tag)).toList();
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.white,
elevation: 0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
title: const Text(
'添加标签',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
content: SizedBox(
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 输入框
TextField(
controller: controller,
autofocus: true,
decoration: const InputDecoration(
hintText: '输入新标签名称',
border: UnderlineInputBorder(),
),
onSubmitted: (value) {
_addTag(value);
Navigator.pop(context);
},
),
// 已有标签列表
if (availableTags.isNotEmpty) ...[
const SizedBox(height: 16),
const Text(
'或选择已有标签:',
style: TextStyle(
fontSize: 12,
color: Color(0xFF999999),
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: availableTags.map((tag) {
return GestureDetector(
onTap: () {
_addTag(tag);
Navigator.pop(context);
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
border: Border.all(color: const Color(0xFFE5E5E5)),
borderRadius: BorderRadius.circular(4),
),
child: Text(
tag,
style: const TextStyle(
fontSize: 13,
color: Color(0xFF666666),
),
),
),
);
}).toList(),
),
],
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消', style: TextStyle(color: Color(0xFF666666))),
),
TextButton(
onPressed: () {
_addTag(controller.text);
Navigator.pop(context);
},
child: const Text('添加'),
),
],
),
);
}
/// 获取所有已有标签(从所有笔记中收集)
List<String> _getAllExistingTags(AppProvider provider) {
final allTags = <String>{};
for (final note in provider.notes) {
allTags.addAll(note.tags);
}
return allTags.toList()..sort();
}
/// 添加标签
void _addTag(String tag) {
final trimmed = tag.trim();
if (trimmed.isNotEmpty && !_tags.contains(trimmed)) {
setState(() => _tags.add(trimmed));
}
}
/// 格式化日期时间
String _formatDateTime(DateTime date) {
return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
}
/// 保存笔记
Future<void> _saveNote() async {
final content = _contentController.text.trim();
if (content.isEmpty) {
ToastUtil.show(context, '笔记内容不能为空');
return;
}
final now = DateTime.now();
if (_isEditing) {
// 更新现有笔记
final updatedNote = widget.note!.copyWith(
content: content,
contentType: _contentType,
tags: _tags,
images: _images,
updatedAt: now,
);
await context.read<AppProvider>().updateNote(updatedNote);
} else {
// 添加新笔记 - 先创建笔记获取ID
final noteId = now.millisecondsSinceEpoch.toString();
// 如果有图片需要移动到正确的ID目录
List<String> finalImages = [];
if (_images.isNotEmpty) {
// 使用保存的临时ID如果没有则使用当前noteId理论上不会走到这里
final oldNoteId = _tempNoteId ?? noteId;
final newNoteId = noteId;
finalImages = await _moveImagesToNewId(oldNoteId, newNoteId);
}
final newNote = Note(
id: noteId,
content: content,
contentType: _contentType,
tags: _tags,
images: finalImages.isNotEmpty ? finalImages : _images,
createdAt: _createdAt,
updatedAt: now,
);
await context.read<AppProvider>().addNote(newNote);
}
if (!mounted) return;
ToastUtil.show(context, _isEditing ? '保存成功' : '添加成功');
Navigator.pop(context);
}
/// 将图片从临时ID目录移动到新ID目录
Future<List<String>> _moveImagesToNewId(String oldNoteId, String newNoteId) async {
final List<String> newPaths = [];
final newDir = await ImagePathHelper.instance.getNoteImagesDir(newNoteId);
for (final imagePath in _images) {
// 使用路径分隔符检查,兼容 Windows 和 Unix
final normalizedPath = imagePath.replaceAll('\\', '/');
if (normalizedPath.contains('/notes/$oldNoteId/')) {
// 需要移动的文件
final fileName = p.basename(imagePath);
final newPath = p.join(newDir, fileName);
await ImagePathHelper.instance.ensureDirExists(newDir);
// 检查源文件是否存在
final sourceFile = File(imagePath);
if (await sourceFile.exists()) {
await sourceFile.rename(newPath);
newPaths.add(newPath);
}
} else {
// 已经在正确位置的文件
newPaths.add(imagePath);
}
}
// 删除旧目录
try {
await ImagePathHelper.instance.deleteNoteImages(oldNoteId);
} catch (e) {
// 忽略删除失败
}
return newPaths;
}
/// 选择图片
Future<void> _pickImage() async {
try {
final XFile? image = await _picker.pickImage(
source: ImageSource.gallery,
maxWidth: 1920,
maxHeight: 1920,
imageQuality: 85,
);
if (image != null) {
// 生成唯一的文件名
final fileName = '${DateTime.now().millisecondsSinceEpoch}.jpg';
// 如果是编辑模式使用现有笔记ID如果是新建模式使用临时ID保存时会替换
String noteId;
if (_isEditing) {
noteId = widget.note!.id;
} else {
// 新建模式使用已存在的临时ID或生成新的
noteId = _tempNoteId ?? DateTime.now().millisecondsSinceEpoch.toString();
_tempNoteId = noteId;
}
// 复制图片到应用目录: images/notes/{noteId}/{fileName}
final targetDir = await ImagePathHelper.instance.getNoteImagesDir(noteId);
await ImagePathHelper.instance.ensureDirExists(targetDir);
final targetPath = p.join(targetDir, fileName);
await File(image.path).copy(targetPath);
setState(() => _images.add(targetPath));
}
} catch (e) {
ToastUtil.show(context, '选择图片失败: $e');
}
}
/// 构建图片项
Widget _buildImageItem(int index) {
return InkWell(
onTap: () => _showImagePreview(index),
onLongPress: () => _showDeleteImageDialog(index),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFFE5E5E5)),
),
child: Image.file(
File(_images[index]),
fit: BoxFit.cover,
),
),
);
}
/// 显示图片预览
void _showImagePreview(int index) {
showDialog(
context: context,
barrierDismissible: true,
builder: (context) => GestureDetector(
onTap: () => Navigator.pop(context),
child: Container(
color: Colors.black.withOpacity(0.9),
child: Center(
child: InteractiveViewer(
panEnabled: true,
boundaryMargin: const EdgeInsets.all(20),
minScale: 0.5,
maxScale: 4,
child: Image.file(
File(_images[index]),
fit: BoxFit.contain,
),
),
),
),
),
);
}
/// 显示删除图片确认对话框
void _showDeleteImageDialog(int index) {
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: () {
setState(() => _images.removeAt(index));
Navigator.pop(context);
},
child: const Text('删除', style: TextStyle(color: Colors.red)),
),
],
),
);
}
}

View File

@@ -0,0 +1,231 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/app_provider.dart';
import '../../models/data_models.dart';
import '../../widgets/note_list_item.dart';
/// 笔记标签页
class NoteTabPage extends StatefulWidget {
const NoteTabPage({super.key});
@override
State<NoteTabPage> createState() => _NoteTabPageState();
}
class _NoteTabPageState extends State<NoteTabPage> {
// 使用分页加载
static const int _pageSize = 50;
final List<Note> _displayedNotes = [];
bool _isLoading = false;
bool _hasMore = true;
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
_scrollController.addListener(_onScroll);
// 延迟加载初始数据避免阻塞UI
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadMoreNotes();
});
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _onScroll() {
if (_scrollController.position.pixels >=
_scrollController.position.maxScrollExtent - 200) {
_loadMoreNotes();
}
}
Future<void> _loadMoreNotes() async {
if (_isLoading || !_hasMore) return;
setState(() => _isLoading = true);
// 使用微任务延迟加载避免阻塞UI
await Future.microtask(() {
final provider = context.read<AppProvider>();
final allNotes = provider.notes;
final startIndex = _displayedNotes.length;
final endIndex = (startIndex + _pageSize).clamp(0, allNotes.length);
if (startIndex >= allNotes.length) {
_hasMore = false;
} else {
final newNotes = allNotes.sublist(startIndex, endIndex);
_displayedNotes.addAll(newNotes);
_hasMore = endIndex < allNotes.length;
}
});
if (mounted) {
setState(() => _isLoading = false);
}
}
Future<void> _refresh() async {
final provider = context.read<AppProvider>();
await provider.loadNotes();
setState(() {
_displayedNotes.clear();
_hasMore = true;
});
await _loadMoreNotes();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
// 笔记列表(分页加载)
Expanded(
child: _buildNoteList(context),
),
],
);
}
/// 构建笔记列表
Widget _buildNoteList(BuildContext context) {
return Consumer<AppProvider>(
builder: (context, provider, child) {
final allNotes = provider.notes;
if (allNotes.isEmpty && _displayedNotes.isEmpty) {
return _buildEmptyState(context);
}
return RefreshIndicator(
onRefresh: _refresh,
color: const Color(0xFF1A1A1A),
backgroundColor: Colors.white,
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
itemCount: _displayedNotes.length + (_hasMore ? 1 : 0),
itemBuilder: (context, index) {
if (index >= _displayedNotes.length) {
// 底部加载指示器
return const Padding(
padding: EdgeInsets.symmetric(vertical: 16),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Color(0xFF1A1A1A),
),
),
),
);
}
return NoteListItem(note: _displayedNotes[index]);
},
),
);
},
);
}
/// 构建空状态提示
Widget _buildEmptyState(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: const Color(0xFFF5F5F5),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(
Icons.note_outlined,
size: 40,
color: Color(0xFFCCCCCC),
),
),
const SizedBox(height: 24),
const Text(
'暂无笔记',
style: TextStyle(
fontSize: 16,
color: Color(0xFF999999),
),
),
const SizedBox(height: 24),
InkWell(
onTap: () {
Navigator.pushNamed(context, '/note-form');
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
decoration: BoxDecoration(
color: const Color(0xFF1A1A1A),
),
child: const Text(
'添加笔记',
style: TextStyle(
fontSize: 14,
color: Colors.white,
),
),
),
),
],
),
);
}
/// 获取示例笔记数据
List<Note> _getSampleNotes() {
final now = DateTime.now();
// 示例数据(实际应从数据库获取)
return [
Note(
id: '1',
content: '今天开始学习 Flutter 框架,感觉和 Vue 有很多相似之处,都是声明式 UI组件化开发。Widget 的概念很有趣,一切皆 Widget。',
tags: ['学习', 'Flutter', '编程'],
createdAt: now.subtract(const Duration(days: 2)),
updatedAt: now.subtract(const Duration(days: 2)),
),
Note(
id: '2',
content: '余华的《活着》真的是一部让人深思的作品。福贵的一生经历了太多的苦难,但他依然坚强地活着。生命的意义或许就在于活着本身。',
tags: ['阅读', '感悟', '书籍'],
createdAt: now.subtract(const Duration(days: 5)),
updatedAt: now.subtract(const Duration(days: 5)),
),
Note(
id: '3',
content: '诺兰的电影总是充满想象力。《星际穿越》将科幻与亲情完美结合,五维空间的呈现方式令人震撼。配乐也是一绝。',
tags: ['观影', '科幻', '电影'],
createdAt: now.subtract(const Duration(days: 10)),
updatedAt: now.subtract(const Duration(days: 10)),
),
Note(
id: '4',
content: 'Pandas 库的 DataFrame 操作非常强大,可以方便地进行数据清洗和分析。需要多练习熟练掌握常用操作。',
tags: ['Python', '数据分析', '技术'],
createdAt: now.subtract(const Duration(days: 30)),
updatedAt: now.subtract(const Duration(days: 30)),
),
Note(
id: '5',
content: '春天来了,天气渐暖。周末去公园散步,看到花开得很好。生活中的小确幸值得记录。',
tags: ['生活', '随笔'],
createdAt: now.subtract(const Duration(hours: 5)),
updatedAt: now.subtract(const Duration(hours: 5)),
),
];
}
}