createCamera method

Future<CameraController?> createCamera({
  1. CameraDescription? cameraDescription,
})

Implementation

Future<CameraController?> createCamera({
  CameraDescription? cameraDescription,
}) async {
  var description = cameraDescription ?? value.cameraDescription;
  var cameras = value.cameras;

  if (description == null) {
    cameras = await availableCameras();
    if (cameras.isNotEmpty) {
      description = cameras[0];
    } else {
      description = const CameraDescription(
        name: 'Simulator',
        lensDirection: CameraLensDirection.front,
        sensorOrientation: 0,
      );
    }
  }

  final controller = CameraController(
    description,
    value.resolutionPreset,
    enableAudio: value.enableAudio,
    imageFormatGroup: value.imageFormatGroup,
  );

  controller.addListener(() {
    if (controller.value.hasError) {
      final error = 'Camera error ${controller.value.errorDescription}';
      _uiHandler.showSnackBar(error);
      _controllerNotifier.value =
          _controllerNotifier.value.copyWith(error: error);
    }
  });

  try {
    await controller.initialize();
    _controllerNotifier.value = ControllerValue(
      controller: controller,
      isReady: true,
    );
    value = value.copyWith(
      cameraDescription: description,
      cameras: cameras,
    );

    if (controller.description.lensDirection == CameraLensDirection.back) {
      controller.setFlashMode(value.flashMode);
    }

    Future.wait([
      controller.getMinExposureOffset().then(exposure.setMinExposure),
      controller.getMaxExposureOffset().then(exposure.setMaxExposure),
      controller.getMaxZoomLevel().then(zoom.setMaxZoom),
      controller.getMinZoomLevel().then(zoom.setMinZoom),
    ]);
  } on CameraException catch (e) {
    _uiHandler.showExceptionSnackbar(e);
  } catch (e) {
    _uiHandler.showSnackBar(e.toString());
  }

  return controller;
}