attachment_picker.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import 'dart:io';
  2. import 'package:flutter/material.dart';
  3. import 'package:image_picker/image_picker.dart';
  4. import 'package:file_picker/file_picker.dart';
  5. import 'package:tdesign_flutter/tdesign_flutter.dart';
  6. import 'package:marquee/marquee.dart';
  7. import '../models/attachment_file.dart';
  8. import '../../core/i18n/app_localizations.dart';
  9. import '../../core/theme/app_colors.dart';
  10. import '../../core/theme/app_colors_extension.dart';
  11. // ═══════════════════════════════════════════════════════════════
  12. // Controller
  13. // ═══════════════════════════════════════════════════════════════
  14. class AttachmentPickerController extends ChangeNotifier {
  15. final int maxCount;
  16. final List<AttachmentFile> _files = [];
  17. List<AttachmentFile> get files => List.unmodifiable(_files);
  18. int get count => _files.length;
  19. bool get isFull => _files.length >= maxCount;
  20. AttachmentPickerController({
  21. this.maxCount = 9,
  22. List<AttachmentFile>? initialFiles,
  23. }) {
  24. if (initialFiles != null) {
  25. _files.addAll(initialFiles.take(maxCount));
  26. }
  27. }
  28. void addFile(AttachmentFile file) {
  29. if (_files.length >= maxCount) return;
  30. _files.add(file);
  31. notifyListeners();
  32. }
  33. void addFiles(List<AttachmentFile> files) {
  34. for (final f in files) {
  35. if (_files.length >= maxCount) break;
  36. _files.add(f);
  37. }
  38. notifyListeners();
  39. }
  40. void removeFile(int index) {
  41. if (index < 0 || index >= _files.length) return;
  42. _files.removeAt(index);
  43. notifyListeners();
  44. }
  45. void clear() {
  46. if (_files.isEmpty) return;
  47. _files.clear();
  48. notifyListeners();
  49. }
  50. /// 从路径列表恢复(草稿兼容)
  51. Future<void> restoreFromPaths(List<String> paths) async {
  52. _files.clear();
  53. for (final path in paths.take(maxCount)) {
  54. _files.add(await AttachmentFile.fromPath(path));
  55. }
  56. notifyListeners();
  57. }
  58. /// 导出为路径列表(草稿持久化)
  59. List<String> toPathList() => _files.map((f) => f.path).toList();
  60. }
  61. // ═══════════════════════════════════════════════════════════════
  62. // Widget
  63. // ═══════════════════════════════════════════════════════════════
  64. class AttachmentPicker extends StatefulWidget {
  65. final AttachmentPickerController controller;
  66. /// 图片大小上限(MB),null 不限制
  67. final double? maxImageSizeMB;
  68. /// 文件大小上限(MB),null 不限制
  69. final double? maxFileSizeMB;
  70. /// 允许的文件扩展名,null 使用默认 pdf/doc/docx/xls/xlsx/ppt/pptx/txt
  71. final List<String>? allowedExtensions;
  72. /// 文件被拒时回调
  73. final void Function(AttachmentFile file, String reason)? onFileRejected;
  74. /// 缩略图尺寸
  75. final double thumbnailSize;
  76. const AttachmentPicker({
  77. super.key,
  78. required this.controller,
  79. this.maxImageSizeMB,
  80. this.maxFileSizeMB,
  81. this.allowedExtensions,
  82. this.onFileRejected,
  83. this.thumbnailSize = 80,
  84. });
  85. @override
  86. State<AttachmentPicker> createState() => _AttachmentPickerState();
  87. }
  88. class _AttachmentPickerState extends State<AttachmentPicker> {
  89. List<AttachmentFile> get _files => widget.controller.files;
  90. @override
  91. void initState() {
  92. super.initState();
  93. widget.controller.addListener(_onChanged);
  94. }
  95. @override
  96. void dispose() {
  97. widget.controller.removeListener(_onChanged);
  98. super.dispose();
  99. }
  100. void _onChanged() {
  101. if (mounted) setState(() {});
  102. }
  103. // ── 选择入口 ──
  104. Future<void> _showPicker() async {
  105. _unfocus();
  106. final l10n = AppLocalizations.of(context);
  107. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  108. final choice = await showModalBottomSheet<String>(
  109. context: context,
  110. backgroundColor: colors.bgCard,
  111. shape: const RoundedRectangleBorder(
  112. borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
  113. ),
  114. builder: (ctx) => SafeArea(
  115. child: Padding(
  116. padding: const EdgeInsets.fromLTRB(0, 8, 0, 20),
  117. child: Column(
  118. mainAxisSize: MainAxisSize.min,
  119. children: [
  120. // 拖拽手柄
  121. Center(
  122. child: Container(
  123. width: 36,
  124. height: 4,
  125. margin: const EdgeInsets.only(bottom: 12),
  126. decoration: BoxDecoration(
  127. color: colors.border,
  128. borderRadius: BorderRadius.circular(2),
  129. ),
  130. ),
  131. ),
  132. // 选择图片
  133. InkWell(
  134. onTap: () => Navigator.pop(ctx, 'image'),
  135. child: Padding(
  136. padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
  137. child: Row(
  138. children: [
  139. Container(
  140. width: 44,
  141. height: 44,
  142. decoration: BoxDecoration(
  143. color: colors.primaryLight,
  144. borderRadius: BorderRadius.circular(12),
  145. ),
  146. child: Icon(Icons.image_outlined, color: colors.primary, size: 24),
  147. ),
  148. const SizedBox(width: 16),
  149. Text(
  150. l10n.get('pickImage'),
  151. style: TextStyle(fontSize: 16, color: colors.textPrimary),
  152. ),
  153. ],
  154. ),
  155. ),
  156. ),
  157. const Divider(height: 1, indent: 76),
  158. // 选择文件
  159. InkWell(
  160. onTap: () => Navigator.pop(ctx, 'file'),
  161. child: Padding(
  162. padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
  163. child: Row(
  164. children: [
  165. Container(
  166. width: 44,
  167. height: 44,
  168. decoration: BoxDecoration(
  169. color: colors.primaryLight,
  170. borderRadius: BorderRadius.circular(12),
  171. ),
  172. child: Icon(Icons.description_outlined, color: colors.primary, size: 24),
  173. ),
  174. const SizedBox(width: 16),
  175. Text(
  176. l10n.get('pickFile'),
  177. style: TextStyle(fontSize: 16, color: colors.textPrimary),
  178. ),
  179. ],
  180. ),
  181. ),
  182. ),
  183. ],
  184. ),
  185. ),
  186. ),
  187. );
  188. if (!mounted || choice == null) return;
  189. if (choice == 'image') {
  190. await _pickImages();
  191. } else {
  192. await _pickDocuments();
  193. }
  194. }
  195. Future<void> _pickImages() async {
  196. final available = widget.controller.maxCount - widget.controller.count;
  197. if (available <= 0) return;
  198. final picker = ImagePicker();
  199. final images = await picker.pickMultiImage(limit: available);
  200. if (!mounted || images.isEmpty) return;
  201. for (final img in images) {
  202. if (widget.controller.isFull) break;
  203. final file = await AttachmentFile.fromXFile(img);
  204. if (_checkOversized(file)) continue;
  205. widget.controller.addFile(file);
  206. }
  207. }
  208. Future<void> _pickDocuments() async {
  209. final available = widget.controller.maxCount - widget.controller.count;
  210. if (available <= 0) return;
  211. final result = await FilePicker.pickFiles(
  212. type: FileType.custom,
  213. allowedExtensions: widget.allowedExtensions ??
  214. const ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'],
  215. allowMultiple: true,
  216. );
  217. if (!mounted || result == null || result.files.isEmpty) return;
  218. for (final pf in result.files) {
  219. if (widget.controller.isFull) break;
  220. if (pf.path == null) continue;
  221. final file = AttachmentFile.fromPlatformFile(pf);
  222. if (_checkOversized(file)) continue;
  223. widget.controller.addFile(file);
  224. }
  225. }
  226. /// 返回 true 表示文件超过大小限制
  227. bool _checkOversized(AttachmentFile file) {
  228. final l10n = AppLocalizations.of(context);
  229. final sizeMB = file.sizeMB;
  230. if (file.isImage && widget.maxImageSizeMB != null && sizeMB > widget.maxImageSizeMB!) {
  231. final reason = l10n.getString('imageSizeLimit', args: {'max': widget.maxImageSizeMB!.toStringAsFixed(0)});
  232. widget.onFileRejected?.call(file, reason);
  233. if (mounted) TDToast.showText(reason, context: context);
  234. return true;
  235. }
  236. if (!file.isImage && widget.maxFileSizeMB != null && sizeMB > widget.maxFileSizeMB!) {
  237. final reason = l10n.getString('fileSizeLimit', args: {'max': widget.maxFileSizeMB!.toStringAsFixed(0)});
  238. widget.onFileRejected?.call(file, reason);
  239. if (mounted) TDToast.showText(reason, context: context);
  240. return true;
  241. }
  242. return false;
  243. }
  244. void _unfocus() => FocusScope.of(context).unfocus();
  245. // ── UI ──
  246. @override
  247. Widget build(BuildContext context) {
  248. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  249. return Column(
  250. crossAxisAlignment: CrossAxisAlignment.start,
  251. children: [
  252. Wrap(
  253. spacing: 8,
  254. runSpacing: 8,
  255. children: [
  256. ..._files.asMap().entries.map(
  257. (e) => Stack(
  258. clipBehavior: Clip.none,
  259. children: [
  260. _buildThumbnail(e.value),
  261. Positioned(
  262. right: -4,
  263. top: -4,
  264. child: GestureDetector(
  265. onTap: () => widget.controller.removeFile(e.key),
  266. child: Container(
  267. width: 20,
  268. height: 20,
  269. decoration: BoxDecoration(
  270. color: colors.danger,
  271. shape: BoxShape.circle,
  272. ),
  273. child: const Icon(
  274. Icons.close,
  275. size: 12,
  276. color: Colors.white,
  277. ),
  278. ),
  279. ),
  280. ),
  281. ],
  282. ),
  283. ),
  284. if (!widget.controller.isFull)
  285. GestureDetector(
  286. onTap: () => _showPicker(),
  287. child: Container(
  288. width: widget.thumbnailSize,
  289. height: widget.thumbnailSize,
  290. decoration: BoxDecoration(
  291. color: colors.bgCard,
  292. borderRadius: BorderRadius.circular(4),
  293. border: Border.all(color: colors.border, width: 1),
  294. ),
  295. child: Center(
  296. child: Icon(
  297. Icons.add,
  298. size: 24,
  299. color: colors.textPlaceholder,
  300. ),
  301. ),
  302. ),
  303. ),
  304. ],
  305. ),
  306. ],
  307. );
  308. }
  309. Widget _buildThumbnail(AttachmentFile file) {
  310. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  311. final size = widget.thumbnailSize;
  312. if (file.isImage) {
  313. return Container(
  314. width: size,
  315. height: size,
  316. decoration: BoxDecoration(
  317. borderRadius: BorderRadius.circular(4),
  318. border: Border.all(color: colors.border, width: 0.5),
  319. ),
  320. child: ClipRRect(
  321. borderRadius: BorderRadius.circular(4),
  322. child: Image.file(
  323. File(file.path),
  324. width: size,
  325. height: size,
  326. fit: BoxFit.cover,
  327. errorBuilder: (_, _, _) => _buildDocTile(file, colors, size),
  328. ),
  329. ),
  330. );
  331. }
  332. return _buildDocTile(file, colors, size);
  333. }
  334. Widget _buildDocTile(AttachmentFile file, AppColorsExtension colors, double size) {
  335. return SizedBox(
  336. width: size,
  337. child: Column(
  338. mainAxisSize: MainAxisSize.min,
  339. children: [
  340. Container(
  341. width: size,
  342. height: size,
  343. decoration: BoxDecoration(
  344. color: colors.primaryLight,
  345. borderRadius: BorderRadius.circular(4),
  346. ),
  347. child: Center(
  348. child: Icon(
  349. _fileTypeIcon(file.extension),
  350. color: colors.primary,
  351. size: size * 0.4,
  352. ),
  353. ),
  354. ),
  355. const SizedBox(height: 4),
  356. SizedBox(
  357. width: size,
  358. height: 16,
  359. child: Marquee(
  360. text: file.name,
  361. style: TextStyle(
  362. fontSize: AppFontSizes.caption,
  363. color: colors.textSecondary,
  364. ),
  365. scrollAxis: Axis.horizontal,
  366. blankSpace: 40,
  367. velocity: 30,
  368. pauseAfterRound: const Duration(seconds: 1),
  369. startPadding: 0,
  370. accelerationDuration: const Duration(milliseconds: 500),
  371. accelerationCurve: Curves.linear,
  372. decelerationDuration: const Duration(milliseconds: 500),
  373. decelerationCurve: Curves.easeOut,
  374. ),
  375. ),
  376. ],
  377. ),
  378. );
  379. }
  380. IconData _fileTypeIcon(String ext) {
  381. switch (ext) {
  382. case 'pdf':
  383. return Icons.picture_as_pdf;
  384. case 'doc':
  385. case 'docx':
  386. return Icons.description;
  387. case 'xls':
  388. case 'xlsx':
  389. return Icons.table_chart;
  390. case 'ppt':
  391. case 'pptx':
  392. return Icons.slideshow;
  393. default:
  394. return Icons.insert_drive_file;
  395. }
  396. }
  397. }