start method

Future<void> start({
  1. CameraFacing? cameraDirection,
})

Start scanning for barcodes.

The cameraDirection can be used to specify the camera direction. If this is null, this defaults to the facing value.

Does nothing if the camera is already running. Upon calling this method, the necessary camera permission will be requested.

If the permission is denied on iOS, MacOS or Web, there is no way to request it again.

Implementation

Future<void> start({CameraFacing? cameraDirection}) async {
  if (_isDisposed) {
    throw const MobileScannerException(
      errorCode: MobileScannerErrorCode.controllerDisposed,
      errorDetails: MobileScannerErrorDetails(
        message:
            'The MobileScannerController was used after it has been disposed.',
      ),
    );
  }

  // Permission was denied, do nothing.
  // When the controller is stopped,
  // the error is reset so the permission can be requested again if possible.
  if (value.error?.errorCode == MobileScannerErrorCode.permissionDenied) {
    return;
  }

  // Do nothing if the camera is already running.
  if (value.isRunning) {
    return;
  }

  final CameraFacing effectiveDirection = cameraDirection ?? facing;

  final StartOptions options = StartOptions(
    cameraDirection: effectiveDirection,
    cameraResolution: cameraResolution,
    detectionSpeed: detectionSpeed,
    detectionTimeoutMs: detectionTimeoutMs,
    formats: formats,
    returnImage: returnImage,
    torchEnabled: torchEnabled,
  );

  try {
    _setupListeners();

    final MobileScannerViewAttributes viewAttributes =
        await MobileScannerPlatform.instance.start(
      options,
    );

    if (!_isDisposed) {
      value = value.copyWith(
        availableCameras: viewAttributes.numberOfCameras,
        cameraDirection: effectiveDirection,
        isInitialized: true,
        isRunning: true,
        size: viewAttributes.size,
        // Provide the current torch state.
        // Updates are provided by the `torchStateStream`.
        torchState: viewAttributes.currentTorchMode,
      );
    }
  } on MobileScannerException catch (error) {
    // The initialization finished with an error.
    // To avoid stale values, reset the output size,
    // torch state and zoom scale to the defaults.
    if (!_isDisposed) {
      value = value.copyWith(
        cameraDirection: facing,
        isInitialized: true,
        isRunning: false,
        error: error,
        size: Size.zero,
        torchState: TorchState.unavailable,
        zoomScale: 1.0,
      );
    }
  } on PermissionRequestPendingException catch (_) {
    // If a permission request was already pending, do nothing.
  }
}