pickFiles method

  1. @override
Future<List<PickedFile>?> pickFiles(
  1. FilePickerOptions options
)
override

Picks files from the device storage based on the provided options.

Platform implementations should override this method to handle file picking on their respective platforms.

Implementation

@override
Future<List<PickedFile>?> pickFiles(FilePickerOptions options) async {
  final completer = Completer<List<PickedFile>?>();

  final input = web.document.createElement('input') as web.HTMLInputElement;
  input.type = 'file';
  input.style.display = 'none';
  input.accept = _acceptString(options.type, options.allowedExtensions);
  input.multiple = options.allowMultiple;
  web.document.body!.append(input);

  // onChange — user confirmed a selection.
  // The handler must be synchronous (void, not Future) for dart:js_interop.
  // We schedule the async work via unawaited to keep the signature valid.
  input.addEventListener(
    'change',
    (web.Event _) {
      _handleFileInputChange(input, options, completer);
    }.toJS,
  );

  // Window focus after dialog close → cancel if nothing was selected
  // Use addEventListener directly because web.Window has no onFocus stream.
  web.window.addEventListener(
    'focus',
    (web.Event _) {
      Future.delayed(const Duration(milliseconds: 500), () {
        if (!completer.isCompleted) {
          final fl = input.files;
          if (fl == null || fl.length == 0) {
            input.remove();
            completer.complete(null);
          }
        }
      });
    }.toJS,
  );

  // Safety timeout
  Future.delayed(const Duration(minutes: 5), () {
    if (!completer.isCompleted) {
      input.remove();
      completer.complete(null);
    }
  });

  input.click();
  return completer.future;
}