forked from edlose16b/flutter_jsonschema_builder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_file_handling.dart
More file actions
392 lines (357 loc) · 11.2 KB
/
Copy pathdemo_file_handling.dart
File metadata and controls
392 lines (357 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_jsonschema_builder/flutter_jsonschema_builder.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
/// Demo-only adapter between the form's file callbacks and platform pickers.
///
/// Applications decide where files come from and what [SchemaFormFile.value]
/// stores. This demo keeps images as data URLs and videos as local paths; a
/// production app would commonly upload the bytes and store the remote key.
Future<List<SchemaFormFile>?> pickDemoFiles(
BuildContext context,
SchemaProperty property,
) async {
final isImage = property.fileType?.toLowerCase() == 'image';
if (!isImage && !property.isVideo) return _pickFromFiles(property);
final source = await _selectFileSource(context, isVideo: property.isVideo);
if (source == null) return null;
if (source == _FileSource.files) return _pickFromFiles(property);
final imageSource =
source == _FileSource.camera ? ImageSource.camera : ImageSource.gallery;
final picker = ImagePicker();
if (property.isVideo) {
final video = await picker.pickVideo(source: imageSource);
return _schemaFilesFromPickerResult(
video == null ? const [] : [video],
isVideo: true,
);
}
final images =
imageSource == ImageSource.gallery && property.isMultipleFile
? await picker.pickMultiImage()
: [
if (await picker.pickImage(source: imageSource) case final image?)
image,
];
return _schemaFilesFromPickerResult(images, isVideo: false);
}
JsonFormSchemaUiConfig buildDemoFileUiConfig() => JsonFormSchemaUiConfig(
filesBuilder: (files, {required onRemove}) {
if (files == null || files.isEmpty) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Wrap(
spacing: 10,
runSpacing: 10,
children: [
for (final file in files)
_DemoFilePreview(file: file, onRemove: onRemove),
],
),
);
},
);
Widget demoReviewFileBuilder(
BuildContext context,
SchemaProperty property,
List<String> values,
) => Wrap(
spacing: 6,
runSpacing: 6,
children: [
for (final value in values)
_DemoReviewFilePreview(value: value, isVideo: property.isVideo),
],
);
Future<List<SchemaFormFile>?> _pickFromFiles(SchemaProperty property) async {
final type =
property.isVideo || property.fileType?.toLowerCase() == 'image'
? FileType.custom
: FileType.any;
final result = await FilePicker.pickFiles(
type: type,
allowedExtensions:
type == FileType.custom
? property.isVideo
? const ['mp4', 'mov', 'm4v', 'webm', '3gp']
: const ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'heic']
: null,
withData: !property.isVideo || kIsWeb,
allowMultiple: property.isMultipleFile,
);
final files = result?.files ?? [];
if (files.isEmpty) return null;
return files
.where((file) => file.bytes != null || file.path != null)
.map(
(file) => SchemaFormFile(
name: file.name,
value:
property.isVideo && file.path != null
? file.path!
: Uri.dataFromBytes(
file.bytes ?? Uint8List(0),
mimeType: _mimeTypeFor(file.name),
).toString(),
bytes: file.bytes ?? Uint8List(0),
),
)
.toList();
}
Future<List<SchemaFormFile>?> _schemaFilesFromPickerResult(
List<XFile> files, {
required bool isVideo,
}) async {
final result = await Future.wait(
files.map((file) async {
final bytes = isVideo ? Uint8List(0) : await file.readAsBytes();
return SchemaFormFile(
name: file.name,
value:
isVideo
? file.path
: Uri.dataFromBytes(
bytes,
mimeType: _mimeTypeFor(file.name),
).toString(),
bytes: bytes,
);
}),
);
return result.isEmpty ? null : result;
}
String _mimeTypeFor(String name) {
const mimeTypes = {
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'png': 'image/png',
'gif': 'image/gif',
'webp': 'image/webp',
'bmp': 'image/bmp',
'heic': 'image/heic',
'mp4': 'video/mp4',
'mov': 'video/quicktime',
'm4v': 'video/x-m4v',
'webm': 'video/webm',
'3gp': 'video/3gpp',
'pdf': 'application/pdf',
};
final extension =
name.contains('.') ? name.split('.').last.toLowerCase() : '';
return mimeTypes[extension] ?? 'application/octet-stream';
}
enum _FileSource { camera, library, files }
Future<_FileSource?> _selectFileSource(
BuildContext context, {
required bool isVideo,
}) {
FocusScope.of(context).unfocus();
return showModalBottomSheet<_FileSource>(
context: context,
showDragHandle: true,
builder:
(context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: Icon(isVideo ? Icons.videocam : Icons.add_a_photo),
title: Text(isVideo ? 'Record video' : 'Take photo'),
onTap: () => Navigator.pop(context, _FileSource.camera),
),
ListTile(
leading: const Icon(Icons.photo_library_outlined),
title: const Text('Photo library'),
onTap: () => Navigator.pop(context, _FileSource.library),
),
ListTile(
leading: const Icon(Icons.folder_outlined),
title: const Text('Files'),
onTap: () => Navigator.pop(context, _FileSource.files),
),
ListTile(
leading: const Icon(Icons.close),
title: const Text('Cancel'),
onTap: () => Navigator.pop(context),
),
],
),
),
);
}
class _DemoFilePreview extends StatelessWidget {
const _DemoFilePreview({required this.file, required this.onRemove});
final SchemaFormFile file;
final ValueChanged<String> onRemove;
@override
Widget build(BuildContext context) {
final mimeType = _mimeTypeFor(file.name);
final Widget preview =
mimeType.startsWith('image/')
? Image.memory(
file.bytes,
key: const Key('demo-image-preview'),
width: 140,
fit: BoxFit.fitWidth,
errorBuilder: (_, __, ___) => const _FileIcon(Icons.image),
)
: mimeType.startsWith('video/')
? _DemoVideoPreview(
key: const Key('demo-video-preview'),
value: file.value,
)
: const _FileIcon(Icons.insert_drive_file_outlined);
return SizedBox(
width: 140,
child: Column(
children: [
Stack(
children: [
ClipRRect(borderRadius: BorderRadius.circular(8), child: preview),
Positioned(
top: 2,
right: 2,
child: IconButton.filledTonal(
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.close, size: 16),
onPressed: () => onRemove(file.value),
),
),
],
),
const SizedBox(height: 4),
Text(file.name, maxLines: 1, overflow: TextOverflow.ellipsis),
],
),
);
}
}
class _DemoVideoPreview extends StatefulWidget {
const _DemoVideoPreview({super.key, required this.value});
final String value;
@override
State<_DemoVideoPreview> createState() => _DemoVideoPreviewState();
}
class _DemoVideoPreviewState extends State<_DemoVideoPreview> {
late final VideoPlayerController _controller;
bool _ready = false;
@override
void initState() {
super.initState();
final uri =
widget.value.startsWith('data:')
? Uri.parse(widget.value)
: Uri.file(widget.value);
_controller = VideoPlayerController.networkUrl(uri);
_initialize();
}
Future<void> _initialize() async {
try {
await _controller.initialize();
await _controller.setLooping(true);
if (mounted) setState(() => _ready = true);
} catch (_) {
// Keep the video icon when a platform cannot preview this file.
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final video = AspectRatio(
aspectRatio:
_ready && _controller.value.aspectRatio > 0
? _controller.value.aspectRatio
: 16 / 9,
child: ColoredBox(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Stack(
alignment: Alignment.center,
children: [
if (_ready)
VideoPlayer(_controller)
else
const Icon(Icons.video_file),
if (_ready)
Icon(
_controller.value.isPlaying
? Icons.pause_circle
: Icons.play_circle,
color: Colors.white,
size: 36,
),
],
),
),
);
return InkWell(
onTap:
!_ready
? null
: () async {
_controller.value.isPlaying
? await _controller.pause()
: await _controller.play();
if (mounted) setState(() {});
},
child: video,
);
}
}
class _DemoReviewFilePreview extends StatelessWidget {
const _DemoReviewFilePreview({required this.value, required this.isVideo});
final String value;
final bool isVideo;
@override
Widget build(BuildContext context) {
if (isVideo) {
return ClipRRect(
borderRadius: BorderRadius.circular(6),
child: ConstrainedBox(
key: const Key('demo-review-video-preview'),
constraints: const BoxConstraints(maxWidth: 64, maxHeight: 64),
child: _DemoVideoPreview(value: value),
),
);
}
Uint8List? bytes;
try {
bytes = Uri.parse(value).data?.contentAsBytes();
} catch (_) {}
return ConstrainedBox(
key: const Key('demo-review-image-preview'),
constraints: const BoxConstraints(maxWidth: 64, maxHeight: 64),
child:
bytes == null
? const _FileIcon(Icons.image, size: 64)
: ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Image.memory(
bytes,
fit: BoxFit.contain,
errorBuilder:
(_, __, ___) => const _FileIcon(Icons.image, size: 64),
),
),
);
}
}
class _FileIcon extends StatelessWidget {
const _FileIcon(this.icon, {this.size = 140});
final IconData icon;
final double size;
@override
Widget build(BuildContext context) => SizedBox(
width: size,
height: size * 9 / 14,
child: ColoredBox(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Icon(icon, size: 40),
),
);
}