initCameras method
Initialize cameras instances. 初始化相机实例
Implementation
void initCameras([CameraDescription? cameraDescription]) {
// Save the current controller to a local variable.
final CameraController? _c = _controller;
// Then unbind the controller from widgets, which requires a build frame.
safeSetState(() {
_maxAvailableZoom = 1;
_minAvailableZoom = 1;
_currentZoom = 1;
_baseZoom = 1;
_controller = null;
// Meanwhile, cancel the existed exposure point and mode display.
_exposureModeDisplayTimer?.cancel();
_exposurePointDisplayTimer?.cancel();
_lastExposurePoint.value = null;
if (_currentExposureOffset.value != 0) {
_currentExposureOffset.value = 0;
}
});
// **IMPORTANT**: Push methods into a post frame callback, which ensures the
// controller has already unbind from widgets.
SchedulerBinding.instance?.addPostFrameCallback((_) async {
// Dispose at last to avoid disposed usage with assertions.
await _c?.dispose();
// When the [cameraDescription] is null, which means this is the first
// time initializing cameras, so available cameras should be fetched.
if (cameraDescription == null) {
cameras = await availableCameras();
}
// After cameras fetched, judge again with the list is empty or not to
// ensure there is at least an available camera for use.
if (cameraDescription == null && (cameras.isEmpty)) {
handleErrorWithHandler(
CameraException(
'No CameraDescription found.',
'No cameras are available in the controller.',
),
widget.onError,
);
}
final int preferredIndex = cameras.indexWhere(
(CameraDescription e) =>
e.lensDirection == widget.preferredLensDirection,
);
final int index;
if (preferredIndex != -1 && _c == null) {
index = preferredIndex;
currentCameraIndex = preferredIndex;
} else {
index = currentCameraIndex;
}
// Initialize the controller with the given resolution preset.
_controller = CameraController(
cameraDescription ?? cameras[index],
widget.resolutionPreset,
enableAudio: enableAudio,
imageFormatGroup: widget.imageFormatGroup,
)..addListener(() {
if (controller.value.hasError) {
handleErrorWithHandler(
CameraException(
'CameraController exception',
controller.value.errorDescription,
),
widget.onError,
);
}
});
try {
await controller.initialize();
if (shouldPrepareForVideoRecording) {
await controller.prepareForVideoRecording();
}
Future.wait(<Future<void>>[
(() async => _maxAvailableExposureOffset =
await controller.getMaxExposureOffset())(),
(() async => _minAvailableExposureOffset =
await controller.getMinExposureOffset())(),
(() async =>
_maxAvailableZoom = await controller.getMaxZoomLevel())(),
(() async =>
_minAvailableZoom = await controller.getMinZoomLevel())(),
]);
} catch (e) {
handleErrorWithHandler(e, widget.onError);
} finally {
safeSetState(() {});
}
});
}