initCameras method
Implementation
void initCameras([CameraDescription? cameraDescription]) {
final _c = _controllerNotifier.value;
setState(() {
_maxAvailableZoom = 1;
_minAvailableZoom = 1;
_currentZoom = 1;
_baseZoom = 1;
_controllerNotifier.value = null;
_exposureModeDisplayTimer?.cancel();
_exposurePointDisplayTimer?.cancel();
_lastExposurePoint.value = null;
if (_currentExposureOffset.value != 0) {
_currentExposureOffset.value = 0;
}
});
// 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)) {
throw CameraException(
'No CameraDescription found.',
'No cameras are available in the controller.',
);
}
// Initialize the controller with the given resolution preset.
_controllerNotifier.value = CameraController(
cameraDescription ?? cameras[0],
widget.resolutionPreset,
enableAudio: enableAudio,
imageFormatGroup: widget.imageFormatGroup,
)..addListener(() {
if (controller.value.hasError) {
throw CameraException(
'CameraController exception',
controller.value.errorDescription,
);
}
});
try {
await controller.initialize();
await Future.wait<void>(<Future<dynamic>>[
(() async => _maxAvailableExposureOffset =
await controller.getMaxExposureOffset())(),
(() async => _minAvailableExposureOffset =
await controller.getMinExposureOffset())(),
(() async =>
_maxAvailableZoom = await controller.getMaxZoomLevel())(),
(() async =>
_minAvailableZoom = await controller.getMinZoomLevel())(),
]);
} catch (_) {
rethrow;
} finally {
safeSetState(() {});
}
});
}