attachment_picker.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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(
  137. horizontal: 16,
  138. vertical: 16,
  139. ),
  140. child: Row(
  141. children: [
  142. Container(
  143. width: 44,
  144. height: 44,
  145. decoration: BoxDecoration(
  146. color: colors.primaryLight,
  147. borderRadius: BorderRadius.circular(12),
  148. ),
  149. child: Icon(
  150. Icons.image_outlined,
  151. color: colors.primary,
  152. size: 24,
  153. ),
  154. ),
  155. const SizedBox(width: 16),
  156. Text(
  157. l10n.get('pickImage'),
  158. style: TextStyle(
  159. fontSize: 16,
  160. color: colors.textPrimary,
  161. ),
  162. ),
  163. ],
  164. ),
  165. ),
  166. ),
  167. const Divider(height: 1, indent: 76),
  168. // 选择文件
  169. InkWell(
  170. onTap: () => Navigator.pop(ctx, 'file'),
  171. child: Padding(
  172. padding: const EdgeInsets.symmetric(
  173. horizontal: 16,
  174. vertical: 16,
  175. ),
  176. child: Row(
  177. children: [
  178. Container(
  179. width: 44,
  180. height: 44,
  181. decoration: BoxDecoration(
  182. color: colors.primaryLight,
  183. borderRadius: BorderRadius.circular(12),
  184. ),
  185. child: Icon(
  186. Icons.description_outlined,
  187. color: colors.primary,
  188. size: 24,
  189. ),
  190. ),
  191. const SizedBox(width: 16),
  192. Text(
  193. l10n.get('pickFile'),
  194. style: TextStyle(
  195. fontSize: 16,
  196. color: colors.textPrimary,
  197. ),
  198. ),
  199. ],
  200. ),
  201. ),
  202. ),
  203. ],
  204. ),
  205. ),
  206. ),
  207. );
  208. if (!mounted || choice == null) return;
  209. if (choice == 'image') {
  210. await _pickImages();
  211. } else {
  212. await _pickDocuments();
  213. }
  214. }
  215. Future<void> _pickImages() async {
  216. final available = widget.controller.maxCount - widget.controller.count;
  217. if (available <= 0) return;
  218. final picker = ImagePicker();
  219. // pickMultiImage 在某些平台上 limit=1 时无响应,兜底用单选
  220. if (available == 1) {
  221. final img = await picker.pickImage(source: ImageSource.gallery);
  222. if (img == null) return;
  223. final file = await AttachmentFile.fromXFile(img);
  224. if (!_checkOversized(file)) widget.controller.addFile(file);
  225. return;
  226. }
  227. final images = await picker.pickMultiImage(limit: available);
  228. if (!mounted || images.isEmpty) return;
  229. for (final img in images) {
  230. if (widget.controller.isFull) break;
  231. final file = await AttachmentFile.fromXFile(img);
  232. if (_checkOversized(file)) continue;
  233. widget.controller.addFile(file);
  234. }
  235. }
  236. Future<void> _pickDocuments() async {
  237. final available = widget.controller.maxCount - widget.controller.count;
  238. if (available <= 0) return;
  239. final result = await FilePicker.pickFiles(
  240. type: FileType.custom,
  241. allowedExtensions:
  242. widget.allowedExtensions ??
  243. const ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'],
  244. allowMultiple: true,
  245. );
  246. if (!mounted || result == null || result.files.isEmpty) return;
  247. if (result.files.length > available) {
  248. final l10n = AppLocalizations.of(context);
  249. TDToast.showText(
  250. l10n.getString('fileLimitHint', args: {'limit': '$available'}),
  251. context: context,
  252. );
  253. }
  254. for (final pf in result.files) {
  255. if (widget.controller.isFull) break;
  256. if (pf.path == null) continue;
  257. final file = AttachmentFile.fromPlatformFile(pf);
  258. if (_checkOversized(file)) continue;
  259. widget.controller.addFile(file);
  260. }
  261. }
  262. /// 返回 true 表示文件超过大小限制
  263. bool _checkOversized(AttachmentFile file) {
  264. final l10n = AppLocalizations.of(context);
  265. final sizeMB = file.sizeMB;
  266. if (file.isImage &&
  267. widget.maxImageSizeMB != null &&
  268. sizeMB > widget.maxImageSizeMB!) {
  269. final reason = l10n.getString(
  270. 'imageSizeLimit',
  271. args: {'max': widget.maxImageSizeMB!.toStringAsFixed(0)},
  272. );
  273. widget.onFileRejected?.call(file, reason);
  274. if (mounted) TDToast.showText(reason, context: context);
  275. return true;
  276. }
  277. if (!file.isImage &&
  278. widget.maxFileSizeMB != null &&
  279. sizeMB > widget.maxFileSizeMB!) {
  280. final reason = l10n.getString(
  281. 'fileSizeLimit',
  282. args: {'max': widget.maxFileSizeMB!.toStringAsFixed(0)},
  283. );
  284. widget.onFileRejected?.call(file, reason);
  285. if (mounted) TDToast.showText(reason, context: context);
  286. return true;
  287. }
  288. return false;
  289. }
  290. void _unfocus() => FocusScope.of(context).unfocus();
  291. // ── UI ──
  292. @override
  293. Widget build(BuildContext context) {
  294. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  295. return Column(
  296. crossAxisAlignment: CrossAxisAlignment.start,
  297. children: [
  298. Wrap(
  299. spacing: 8,
  300. runSpacing: 8,
  301. children: [
  302. ..._files.asMap().entries.map(
  303. (e) => Stack(
  304. clipBehavior: Clip.none,
  305. children: [
  306. _buildThumbnail(e.value),
  307. Positioned(
  308. right: -4,
  309. top: -4,
  310. child: GestureDetector(
  311. onTap: () => widget.controller.removeFile(e.key),
  312. child: Container(
  313. width: 20,
  314. height: 20,
  315. decoration: BoxDecoration(
  316. color: colors.danger,
  317. shape: BoxShape.circle,
  318. ),
  319. child: const Icon(
  320. Icons.close,
  321. size: 12,
  322. color: Colors.white,
  323. ),
  324. ),
  325. ),
  326. ),
  327. ],
  328. ),
  329. ),
  330. if (!widget.controller.isFull)
  331. GestureDetector(
  332. onTap: () => _showPicker(),
  333. child: Container(
  334. width: widget.thumbnailSize,
  335. height: widget.thumbnailSize,
  336. decoration: BoxDecoration(
  337. color: colors.bgCard,
  338. borderRadius: BorderRadius.circular(4),
  339. border: Border.all(color: colors.border, width: 1),
  340. ),
  341. child: Center(
  342. child: Icon(
  343. Icons.add,
  344. size: 24,
  345. color: colors.textPlaceholder,
  346. ),
  347. ),
  348. ),
  349. ),
  350. ],
  351. ),
  352. ],
  353. );
  354. }
  355. Widget _buildThumbnail(AttachmentFile file) {
  356. final colors = Theme.of(context).extension<AppColorsExtension>()!;
  357. final size = widget.thumbnailSize;
  358. if (file.isImage) {
  359. return Container(
  360. width: size,
  361. height: size,
  362. decoration: BoxDecoration(
  363. borderRadius: BorderRadius.circular(4),
  364. border: Border.all(color: colors.border, width: 0.5),
  365. ),
  366. child: ClipRRect(
  367. borderRadius: BorderRadius.circular(4),
  368. child: Image.file(
  369. File(file.path),
  370. width: size,
  371. height: size,
  372. fit: BoxFit.cover,
  373. errorBuilder: (_, _, _) => _buildDocTile(file, colors, size),
  374. ),
  375. ),
  376. );
  377. }
  378. return _buildDocTile(file, colors, size);
  379. }
  380. Widget _buildDocTile(
  381. AttachmentFile file,
  382. AppColorsExtension colors,
  383. double size,
  384. ) {
  385. return SizedBox(
  386. width: size,
  387. child: Column(
  388. mainAxisSize: MainAxisSize.min,
  389. children: [
  390. Container(
  391. width: size,
  392. height: size,
  393. decoration: BoxDecoration(
  394. color: colors.primaryLight,
  395. borderRadius: BorderRadius.circular(4),
  396. ),
  397. child: Center(
  398. child: Icon(
  399. _fileTypeIcon(file.extension),
  400. color: colors.primary,
  401. size: size * 0.4,
  402. ),
  403. ),
  404. ),
  405. const SizedBox(height: 4),
  406. SizedBox(
  407. width: size,
  408. height:
  409. MediaQuery.textScalerOf(context).scale(AppFontSizes.caption) *
  410. 1.4,
  411. child: Marquee(
  412. text: file.name,
  413. style: TextStyle(
  414. fontSize: AppFontSizes.caption,
  415. color: colors.textSecondary,
  416. ),
  417. scrollAxis: Axis.horizontal,
  418. blankSpace: 40,
  419. velocity: 30,
  420. pauseAfterRound: const Duration(seconds: 1),
  421. startPadding: 0,
  422. accelerationDuration: const Duration(milliseconds: 500),
  423. accelerationCurve: Curves.linear,
  424. decelerationDuration: const Duration(milliseconds: 500),
  425. decelerationCurve: Curves.easeOut,
  426. ),
  427. ),
  428. ],
  429. ),
  430. );
  431. }
  432. IconData _fileTypeIcon(String ext) {
  433. switch (ext) {
  434. case 'pdf':
  435. return Icons.picture_as_pdf;
  436. case 'doc':
  437. case 'docx':
  438. return Icons.description;
  439. case 'xls':
  440. case 'xlsx':
  441. return Icons.table_chart;
  442. case 'ppt':
  443. case 'pptx':
  444. return Icons.slideshow;
  445. default:
  446. return Icons.insert_drive_file;
  447. }
  448. }
  449. }