I have a desktop project which allow users to take picture using external camera. I keep getting the following error when i use an external camera. Error flutter: CameraException(camera_error, Camera with given device id already exists. Existing camera must be disposed before creating it again.).
When i use the internal camera of the laptop i do no get this error. I have tried with different cameras and i still get the same error.
My Code Here i get all cameras
initCamera() async {
try {
if (controller != null) {
await controller!.dispose();
}
cameras = await availableCameras();
selectedCamera = cameras.isNotEmpty ? cameras[0] : null;
setState(() {});
} catch (e) {
CustomDialog.showError(message: 'Camera Error');
}
}
Here i change the camera from a dropdown of cameras
void changeCamera(CameraDescription cameraDescription) async {
if (controller != null) {
await controller!.dispose();
}
setState(() {
controller =
CameraController(cameraDescription, ResolutionPreset.ultraHigh);
selectedCamera = cameraDescription;
isCameraOn = false;
});
}
Here is where i initilize and start the camera
void startCamera() async {
try {
await controller?.dispose();
controller = CameraController(
selectedCamera!,
ResolutionPreset.max,
enableAudio: false,
);
await controller!.initialize();
isCameraOn = true;
setState(() {});
} catch (e) {
CustomDialog.showError(
message: 'Camera error, Remove camera and try again');
print(e.toString());
}
}
Here i dispose the camera
void disposeCurrentCamera() async {
await controller?.dispose();
controller = null;
isCameraOn = false;
setState(() {});
}
And i take the image here
snapPicture() async {
if (!isCameraOn) {
return;
}
final image= await controller!.takePicture();
setState(() {
isCameraOn = false;
});
}
when i use an external camera, its works once for the first time and get stack here
controller = CameraController(
selectedCamera!,
ResolutionPreset.max,
enableAudio: false,
);
And it never works again even if i take it out and put it in back unless i kill the application and rerun it.
I have tried using different external cameras and it doesnt work.