initializeCamera method Null safety
- int cameraId,
- {ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown}
override
Initializes the camera on the device.
imageFormatGroup
is used to specify the image formatting used.
On Android this defaults to ImageFormat.YUV_420_888 and applies only to the imageStream.
On iOS this defaults to kCVPixelFormatType_32BGRA.
On Web this parameter is currently not supported.
Implementation
@override
Future<void> initializeCamera(
int cameraId, {
// The image format group is currently not supported.
ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown,
}) async {
try {
final Camera camera = getCamera(cameraId);
await camera.initialize();
// Add camera's video error events to the camera events stream.
// The error event fires when the video element's source has failed to load, or can't be used.
_cameraVideoErrorSubscriptions[cameraId] =
camera.videoElement.onError.listen((html.Event _) {
// The Event itself (_) doesn't contain information about the actual error.
// We need to look at the HTMLMediaElement.error.
// See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/error
final html.MediaError error = camera.videoElement.error!;
final CameraErrorCode errorCode = CameraErrorCode.fromMediaError(error);
final String? errorMessage =
error.message != '' ? error.message : _kDefaultErrorMessage;
cameraEventStreamController.add(
CameraErrorEvent(
cameraId,
'Error code: $errorCode, error message: $errorMessage',
),
);
});
// Add camera's video abort events to the camera events stream.
// The abort event fires when the video element's source has not fully loaded.
_cameraVideoAbortSubscriptions[cameraId] =
camera.videoElement.onAbort.listen((html.Event _) {
cameraEventStreamController.add(
CameraErrorEvent(
cameraId,
"Error code: ${CameraErrorCode.abort}, error message: The video element's source has not fully loaded.",
),
);
});
await camera.play();
// Add camera's closing events to the camera events stream.
// The onEnded stream fires when there is no more camera stream data.
_cameraEndedSubscriptions[cameraId] =
camera.onEnded.listen((html.MediaStreamTrack _) {
cameraEventStreamController.add(
CameraClosingEvent(cameraId),
);
});
final Size cameraSize = camera.getVideoSize();
cameraEventStreamController.add(
CameraInitializedEvent(
cameraId,
cameraSize.width,
cameraSize.height,
// TODO(bselwe): Add support for exposure mode and point (https://github.com/flutter/flutter/issues/86857).
ExposureMode.auto,
false,
// TODO(bselwe): Add support for focus mode and point (https://github.com/flutter/flutter/issues/86858).
FocusMode.auto,
false,
),
);
} on html.DomException catch (e) {
throw PlatformException(code: e.name, message: e.message);
} on CameraWebException catch (e) {
_addCameraErrorEvent(e);
throw PlatformException(code: e.code.toString(), message: e.description);
}
}