pickFile method
Pick a file from the device
If camera
is true then the camera will open
Implementation
void pickFile(
DefaultAttachmentTypes fileType, {
bool camera = false,
}) async {
setState(() => _inputEnabled = false);
AttachmentFile? file;
String? attachmentType;
if (fileType == DefaultAttachmentTypes.image) {
attachmentType = 'image';
} else if (fileType == DefaultAttachmentTypes.video) {
attachmentType = 'video';
} else if (fileType == DefaultAttachmentTypes.file) {
attachmentType = 'file';
}
if (camera) {
XFile? pickedFile;
if (fileType == DefaultAttachmentTypes.image) {
pickedFile = await _imagePicker.pickImage(source: ImageSource.camera);
} else if (fileType == DefaultAttachmentTypes.video) {
pickedFile = await _imagePicker.pickVideo(source: ImageSource.camera);
}
if (pickedFile != null) {
final bytes = await pickedFile.readAsBytes();
file = AttachmentFile(
size: bytes.length,
path: pickedFile.path,
bytes: bytes,
);
}
} else {
late FileType type;
if (fileType == DefaultAttachmentTypes.image) {
type = FileType.image;
} else if (fileType == DefaultAttachmentTypes.video) {
type = FileType.video;
} else if (fileType == DefaultAttachmentTypes.file) {
type = FileType.any;
}
final res = await FilePicker.platform.pickFiles(
type: type,
);
if (res?.files.isNotEmpty == true) {
file = res!.files.single.toAttachmentFile;
}
}
setState(() => _inputEnabled = true);
if (file == null) return;
final mimeType = file.name?.mimeType ?? file.path!.split('/').last.mimeType;
final extraDataMap = <String, Object>{};
if (mimeType?.subtype != null) {
extraDataMap['mime_type'] = mimeType!.subtype.toLowerCase();
}
extraDataMap['file_size'] = file.size!;
final attachment = Attachment(
file: file,
type: attachmentType,
uploadState: const UploadState.preparing(),
extraData: extraDataMap,
);
if (file.size! > widget.maxAttachmentSize) {
if (attachmentType == 'video' && file.path != null) {
final mediaInfo = await (VideoService.compressVideo(
file.path!,
frameRate: widget.compressedVideoFrameRate,
quality: widget.compressedVideoQuality,
) as FutureOr<MediaInfo>);
if (mediaInfo.filesize! > widget.maxAttachmentSize) {
_showErrorAlert(
context.translations.fileTooLargeAfterCompressionError(
widget.maxAttachmentSize / (1024 * 1024),
),
);
return;
}
file = AttachmentFile(
name: file.name,
size: mediaInfo.filesize,
bytes: await mediaInfo.file!.readAsBytes(),
path: mediaInfo.path,
);
} else {
_showErrorAlert(context.translations.fileTooLargeError(
widget.maxAttachmentSize / (1024 * 1024),
));
return;
}
}
setState(() {
_addAttachments([
attachment.copyWith(
file: file,
extraData: {...attachment.extraData}
..update('file_size', ((_) => file!.size!)),
),
]);
});
}