takePicture method

Future<void> takePicture()

The picture will only taken when CameraValue.isInitialized, and the camera is not taking pictures. 仅当初始化成功且相机未在拍照时拍照。

Implementation

Future<void> takePicture() async {
  if (!controller.value.isInitialized) {
    handleErrorWithHandler(
      StateError('Camera has not initialized.'),
      StackTrace.current,
      pickerConfig.onError,
    );
  }
  if (isControllerBusy) {
    return;
  }
  setState(() {
    isControllerBusy = true;
    isShootingButtonAnimate = true;
  });
  final ExposureMode previousExposureMode = controller.value.exposureMode;
  try {
    await Future.wait(<Future<void>>[
      wrapControllerMethod<void>(
        'setFocusMode',
        () => controller.setFocusMode(FocusMode.locked),
      ).catchError((e, s) {
        handleErrorWithHandler(e, s, pickerConfig.onError);
      }),
      if (previousExposureMode != ExposureMode.locked)
        wrapControllerMethod<void>(
          'setExposureMode',
          () => controller.setExposureMode(ExposureMode.locked),
        ).catchError((e, s) {
          handleErrorWithHandler(e, s, pickerConfig.onError);
        }),
    ]);
    final XFile file = await controller.takePicture();
    await controller.pausePreview();
    final bool? isCapturedFileHandled = pickerConfig.onXFileCaptured?.call(
      file,
      CameraPickerViewType.image,
    );
    if (isCapturedFileHandled ?? false) {
      return;
    }
    final AssetEntity? entity = await pushToViewer(
      file: file,
      viewType: CameraPickerViewType.image,
    );
    if (entity != null) {
      Navigator.of(context).pop(entity);
      return;
    }
    await Future.wait(<Future<void>>[
      wrapControllerMethod<void>(
        'setFocusMode',
        () => controller.setFocusMode(FocusMode.auto),
      ),
      if (previousExposureMode != ExposureMode.locked)
        wrapControllerMethod<void>(
          'setExposureMode',
          () => controller.setExposureMode(previousExposureMode),
        ),
    ]);
    await controller.resumePreview();
  } catch (e, s) {
    handleErrorWithHandler(e, s, pickerConfig.onError);
  } finally {
    safeSetState(() {
      isControllerBusy = false;
      isShootingButtonAnimate = false;
    });
  }
}