initialize method Null safety

Future<void> initialize()

Initializes the camera on the device.

Throws a CameraException if the initialization fails.

Implementation

Future<void> initialize() async {
  if (_isDisposed) {
    throw CameraException(
      'Disposed CameraController',
      'initialize was called on a disposed CameraController',
    );
  }
  try {
    final Completer<CameraInitializedEvent> _initializeCompleter =
        Completer<CameraInitializedEvent>();

    _deviceOrientationSubscription = CameraPlatform.instance
        .onDeviceOrientationChanged()
        .listen((DeviceOrientationChangedEvent event) {
      value = value.copyWith(
        deviceOrientation: event.orientation,
      );
    });

    _cameraId = await CameraPlatform.instance.createCamera(
      description,
      resolutionPreset,
      enableAudio: enableAudio,
    );

    _unawaited(CameraPlatform.instance
        .onCameraInitialized(_cameraId)
        .first
        .then((CameraInitializedEvent event) {
      _initializeCompleter.complete(event);
    }));

    await CameraPlatform.instance.initializeCamera(
      _cameraId,
      imageFormatGroup: imageFormatGroup ?? ImageFormatGroup.unknown,
    );

    value = value.copyWith(
      isInitialized: true,
      previewSize: await _initializeCompleter.future
          .then((CameraInitializedEvent event) => Size(
                event.previewWidth,
                event.previewHeight,
              )),
      exposureMode: await _initializeCompleter.future
          .then((CameraInitializedEvent event) => event.exposureMode),
      focusMode: await _initializeCompleter.future
          .then((CameraInitializedEvent event) => event.focusMode),
      exposurePointSupported: await _initializeCompleter.future.then(
          (CameraInitializedEvent event) => event.exposurePointSupported),
      focusPointSupported: await _initializeCompleter.future
          .then((CameraInitializedEvent event) => event.focusPointSupported),
    );
  } on PlatformException catch (e) {
    throw CameraException(e.code, e.message);
  }

  _initCalled = true;
}