selectFileFromGallery static method

Future<void> selectFileFromGallery({
  1. required BuildContext context,
  2. required UploadReturnId uploadAndReturnIdFunction,
  3. required Function toggleUpload,
  4. required String fileTitle,
  5. required void updateUIFunc(
    1. File file,
    2. String uploadId
    ),
})

Selects a file from the gallery

Takes a BuildContext that is used to show alert messages using the ScaffoldMessenger.of(context).showSnackBar() method.

The UploadReturnId is used to upload the file

The fileTitle is the name of the upload to be used

The updateUIFunc returns a File object and the uploadId so that the UI can be refreshed with the updated values after uploading the file

Implementation

static Future<void> selectFileFromGallery({
  required BuildContext context,
  required UploadReturnId uploadAndReturnIdFunction,
  required Function toggleUpload,
  required String fileTitle,
  required void Function(File file, String uploadId) updateUIFunc,
}) async {
  PickedFile? pickedFile;

  try {
    // ignore: deprecated_member_use
    pickedFile = await ImagePicker().getImage(
      source: ImageSource.gallery,
      imageQuality: 50,
    );
  } catch (e) {
    ScaffoldMessenger.of(context)
        .showSnackBar(snackbar(content: UserFeedBackTexts.selectFileError));
    return;
  }

  if (pickedFile != null) {
    /// checks that [result.files] has one file and returns that file
    final File selectedFile = File(pickedFile.path);
    final int selectedFileSizeInKb = await getFileSize(selectedFile);

    if (selectedFileSizeInKb > fileUploadSizeThresholdInKb) {
      // User canceled the picker
      ScaffoldMessenger.of(context)
          .showSnackBar(snackbar(content: tooLargeImageError));
      return;
    }

    toggleUpload();

    /// uploads the file and returns an [uploadID]
    final String uploadId = await uploadAndReturnIdFunction(
        fileData: getFileData(file: selectedFile, fileTitle: fileTitle),
        context: context);
    toggleUpload();

    if (uploadId == 'err') {
      ScaffoldMessenger.of(context)
          .showSnackBar(snackbar(content: UserFeedBackTexts.uploadFileFail));
      return;
    }
    updateUIFunc(selectedFile, uploadId);
  } else {
    // The user canceled the picker so we alert them
    ScaffoldMessenger.of(context)
        .showSnackBar(snackbar(content: UserFeedBackTexts.noFileSelected));
  }
}