takePhoto method

  1. @override
Future<AdaptiveFile?> takePhoto(
  1. PickerOptions options
)
override

Captures a photo using the device camera.

Implementation

@override
Future<AdaptiveFile?> takePhoto(PickerOptions options) async {
  final completer = Completer<AdaptiveFile?>();

  final input = web.document.createElement('input') as web.HTMLInputElement;
  input.type = 'file';
  input.accept = 'image/*';
  input.style.display = 'none';

  // Specify capture device
  if (options.preferredCameraDevice == CameraDevice.front) {
    input.setAttribute('capture', 'user');
  } else {
    input.setAttribute('capture', 'environment');
  }

  input.onchange = ((web.Event event) {
    final fileList = input.files;
    if (fileList == null || fileList.length == 0) {
      if (!completer.isCompleted) completer.complete(null);
      input.remove();
      return;
    }

    final web.File? file = fileList.item(0);
    if (file == null) {
      if (!completer.isCompleted) completer.complete(null);
      input.remove();
      return;
    }

    _readWebFile(file).then((adaptiveFile) {
      if (!completer.isCompleted) completer.complete(adaptiveFile);
    }).catchError((err) {
      if (!completer.isCompleted) completer.completeError(err);
    }).whenComplete(() {
      input.remove();
    });
  }).toJS;

  web.document.body?.appendChild(input);
  input.click();

  return completer.future;
}