attachment_picker.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. // pickMultiImage 在某些平台上 limit=1 时无响应,兜底用单选
  200. if (available == 1) {
  201. final img = await picker.pickImage(source: ImageSource.gallery);
  202. if (img == null) return;
  203. final file = await AttachmentFile.fromXFile(img);
  204. if (!_checkOversized(file)) widget.controller.addFile(file);
  205. return;
  206. }
  207. final images = await picker.pickMultiImage(limit: available);
  208. if (!mounted || images.isEmpty) return;
  209. for (final img in images) {
  210. if (widget.controller.isFull) break;
  211. final file = await AttachmentFile.fromXFile(img);
  212. if (_checkOversized(file)) continue;
  213. widget.controller.addFile(file);
  214. }
  215. }
  216. Future<void> _pickDocuments() async {
  217. final available = widget.controller.maxCount - widget.controller.count;
  218. if (available <= 0) return;
  219. final result = await FilePicker.pickFiles(
  220. type: FileType.custom,
  221. allowedExtensions: widget.allowedExtensions ??
  222. const ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'],
  223. allowMultiple: true,
  224. );
  225. if (!mounted || result == null || result.files.isEmpty) return;
  226. if (result.files.length > available) {
  227. final l10n = AppLocalizations.of(context);
  228. TDToast.showText(l10n.getString('fileLimitHint', args: {'limit': '$available'}), context: context);
  229. }
  230. for (final pf in result.files) {
  231. if (widget.controller.isFull) break;
  232. if (pf.path == null) continue;
  233. final file = AttachmentFile.fromPlatformFile(pf);
  234. if (_checkOversized(file)) continue;
  235. widget.controller.addFile(file);
  236. }
  237. }
  238. /// 返回 true 表示文件超过大小限制
  239. bool _checkOversized(AttachmentFile file) {
  240. final l10n = AppLocalizations.of(context);
  241. final sizeMB = file.sizeMB;
  242. if (file.isImage && widget.maxImageSizeMB != null && sizeMB > widget.maxImageSizeMB!) {
  243. final reason = l10n.getString('imageSizeLimit', args: {'max': widget.maxImageSizeMB!.toStringAsFixed(0)});
  244. widget.onFileRejected?.call(file, reason);
  245. if (mounted) TDToast.showText(reason, context: context);
  246. return true;
  247. }
  248. if (!file.isImage && widget.maxFileSizeMB != null && sizeMB > widget.maxFileSizeMB!) {
  249. final reason = l10n.getString('fileSizeLimit', args: {'max': widget.maxFileSizeMB!.toStringAsFixed(0)});
  250. widget.onFileRejected?.call(file, reason);
  251. if (mounted) TDToast.showText(reason, context: context);
  252. return true;
  253. }
  254. return false;
  255. }
  256. void _unfocus() => FocusScope.of(context).unfocus();
  257. // ── UI ──
  258. @override
  259. Widget build(BuildContext context) {
  260. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  261. return Column(
  262. crossAxisAlignment: CrossAxisAlignment.start,
  263. children: [
  264. Wrap(
  265. spacing: 8,
  266. runSpacing: 8,
  267. children: [
  268. ..._files.asMap().entries.map(
  269. (e) => Stack(
  270. clipBehavior: Clip.none,
  271. children: [
  272. _buildThumbnail(e.value),
  273. Positioned(
  274. right: -4,
  275. top: -4,
  276. child: GestureDetector(
  277. onTap: () => widget.controller.removeFile(e.key),
  278. child: Container(
  279. width: 20,
  280. height: 20,
  281. decoration: BoxDecoration(
  282. color: colors.danger,
  283. shape: BoxShape.circle,
  284. ),
  285. child: const Icon(
  286. Icons.close,
  287. size: 12,
  288. color: Colors.white,
  289. ),
  290. ),
  291. ),
  292. ),
  293. ],
  294. ),
  295. ),
  296. if (!widget.controller.isFull)
  297. GestureDetector(
  298. onTap: () => _showPicker(),
  299. child: Container(
  300. width: widget.thumbnailSize,
  301. height: widget.thumbnailSize,
  302. decoration: BoxDecoration(
  303. color: colors.bgCard,
  304. borderRadius: BorderRadius.circular(4),
  305. border: Border.all(color: colors.border, width: 1),
  306. ),
  307. child: Center(
  308. child: Icon(
  309. Icons.add,
  310. size: 24,
  311. color: colors.textPlaceholder,
  312. ),
  313. ),
  314. ),
  315. ),
  316. ],
  317. ),
  318. ],
  319. );
  320. }
  321. Widget _buildThumbnail(AttachmentFile file) {
  322. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  323. final size = widget.thumbnailSize;
  324. if (file.isImage) {
  325. return Container(
  326. width: size,
  327. height: size,
  328. decoration: BoxDecoration(
  329. borderRadius: BorderRadius.circular(4),
  330. border: Border.all(color: colors.border, width: 0.5),
  331. ),
  332. child: ClipRRect(
  333. borderRadius: BorderRadius.circular(4),
  334. child: Image.file(
  335. File(file.path),
  336. width: size,
  337. height: size,
  338. fit: BoxFit.cover,
  339. errorBuilder: (_, _, _) => _buildDocTile(file, colors, size),
  340. ),
  341. ),
  342. );
  343. }
  344. return _buildDocTile(file, colors, size);
  345. }
  346. Widget _buildDocTile(AttachmentFile file, AppColorsExtension colors, double size) {
  347. return SizedBox(
  348. width: size,
  349. child: Column(
  350. mainAxisSize: MainAxisSize.min,
  351. children: [
  352. Container(
  353. width: size,
  354. height: size,
  355. decoration: BoxDecoration(
  356. color: colors.primaryLight,
  357. borderRadius: BorderRadius.circular(4),
  358. ),
  359. child: Center(
  360. child: Icon(
  361. _fileTypeIcon(file.extension),
  362. color: colors.primary,
  363. size: size * 0.4,
  364. ),
  365. ),
  366. ),
  367. const SizedBox(height: 4),
  368. SizedBox(
  369. width: size,
  370. height: 16,
  371. child: Marquee(
  372. text: file.name,
  373. style: TextStyle(
  374. fontSize: AppFontSizes.caption,
  375. color: colors.textSecondary,
  376. ),
  377. scrollAxis: Axis.horizontal,
  378. blankSpace: 40,
  379. velocity: 30,
  380. pauseAfterRound: const Duration(seconds: 1),
  381. startPadding: 0,
  382. accelerationDuration: const Duration(milliseconds: 500),
  383. accelerationCurve: Curves.linear,
  384. decelerationDuration: const Duration(milliseconds: 500),
  385. decelerationCurve: Curves.easeOut,
  386. ),
  387. ),
  388. ],
  389. ),
  390. );
  391. }
  392. IconData _fileTypeIcon(String ext) {
  393. switch (ext) {
  394. case 'pdf':
  395. return Icons.picture_as_pdf;
  396. case 'doc':
  397. case 'docx':
  398. return Icons.description;
  399. case 'xls':
  400. case 'xlsx':
  401. return Icons.table_chart;
  402. case 'ppt':
  403. case 'pptx':
  404. return Icons.slideshow;
  405. default:
  406. return Icons.insert_drive_file;
  407. }
  408. }
  409. }