pickImageFile function

Future<Uint8List?> pickImageFile()

The browser's file dialog for one image; null when the visitor picks nothing.

Implementation

Future<Uint8List?> pickImageFile() {
  final input = web.HTMLInputElement()
    ..type = 'file'
    ..accept = 'image/*';
  final picked = Completer<Uint8List?>();
  void done(Uint8List? bytes) {
    if (!picked.isCompleted) picked.complete(bytes);
  }

  input.onchange = ((web.Event _) {
    final file = input.files?.item(0);
    if (file == null) {
      done(null);
      return;
    }
    file.arrayBuffer().toDart.then(
      (buffer) => done(buffer.toDart.asUint8List()),
      onError: (Object _) => done(null),
    );
  }).toJS;
  // A dialog closed without a file fires cancel, not change.
  input.oncancel = ((web.Event _) => done(null)).toJS;
  input.click();
  return picked.future;
}