flutterFilePicker static method

Future<List<ChosenMedia>> flutterFilePicker(
  1. BuildContext context, {
  2. int? maxSelections = 1,
  3. VoidCallback? onLoading,
  4. FlutterMediaContentType<Object>? mediaType,
  5. Set<FileSourceType>? sourceTypes,
  6. dynamic extraOptions,
})

Implementation

static Future<List<ChosenMedia>> flutterFilePicker(
  BuildContext context, {
  int? maxSelections = 1,
  VoidCallback? onLoading,
  FlutterMediaContentType? mediaType,

  /// By default will show all available
  Set<FileSourceType>? sourceTypes,
  dynamic extraOptions,
}) async {
  List<ChosenMedia> res;
  var hasStartedReading = false;

  var fileType = mediaType == FlutterMediaTypes.videoExt
      ? FileType.video
      : mediaType == FlutterMediaTypes.imageExt
          ? FileType.image
          : FileType.any;

  sourceTypes ??= {
    const FileSourceType.files(),
    if (!kIsWeb) const FileSourceType.gallery(),
    const FileSourceType.url(),
  };
  assert(sourceTypes.length > 0);

  FileSourceType? sourceType = sourceTypes.length == 1
      ? sourceTypes.first
      : (await showPicker(context,
              options: {
                for (var option in sourceTypes) option.toOption(),
              },
              extraOptions: extraOptions))
          ?.value;

  if (sourceType == null) {
    return [];
  }

  if (sourceType == const FileSourceType.files()) {
    final sel = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: mediaType!.acceptedFileTypes,
        dialogTitle: "Choose an image",
        withData: false,
        // allowCompression: true,
        withReadStream: true,
        allowCompression: true,
        allowMultiple: maxSelections! > 1,
        onFileLoading: (_) {
          if (!hasStartedReading) {
            hasStartedReading = true;
            onLoading?.call();
          }
        });
    res = [...?sel?.files.map((file) => ChosenMedia.ofFile(file))];
  } else if (sourceType == const FileSourceType.gallery()) {
    final sel = await FilePicker.platform.pickFiles(
        type: fileType,
        // allowCompression: true,
        withReadStream: true,
        allowCompression: true,
        allowMultiple: maxSelections! > 1,
        onFileLoading: (_) {
          if (!hasStartedReading) {
            hasStartedReading = true;
            onLoading?.call();
          }
          _log.info("File is loading... $_");
        });

    res = [...?sel?.files.map((file) => ChosenMedia.ofFile(file))];
  } else if (sourceType == const FileSourceType.url()) {
    final sel = await showMediaUrlForm(context, mediaType: mediaType);
    res = [
      if (sel != null) ChosenMedia.ofContent(sel as IContent),
    ];
  } else {
    throw "Illegal state.  Invalid choice: ${sourceType}";
  }

  return res;
}