switchCamera static method
Switch between front and back cameras
Implementation
static Future<void> switchCamera() async {
if (_cameras.length <= 1) return;
try {
// Cancel face detection timer while switching
_faceDetectionTimer?.cancel();
final currentCamera = _cameraController?.description;
final newCamera = _cameras.firstWhere(
(camera) => camera.lensDirection != currentCamera?.lensDirection,
orElse: () => _cameras.first,
);
// Safely dispose the old controller
if (_cameraController != null) {
if (_cameraController!.value.isInitialized) {
await _cameraController!.dispose();
}
_cameraController = null;
}
_cameraController = CameraController(
newCamera,
ResolutionPreset.medium,
enableAudio: false,
);
await _cameraController!.initialize();
// Restart face detection
startFaceDetection();
} catch (e) {
print('Camera switch error: $e');
// Don't throw, just log the error to prevent UI crashes
}
}