Skip to content

Commit c8570fc

Browse files
authored
fix: disposed CameraController error thrown when changing a camera (flutter#4236)
1 parent b1c65df commit c8570fc

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

packages/camera/camera/example/lib/main.dart

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -594,17 +594,21 @@ class _CameraExampleHomeState extends State<CameraExampleHome>
594594
}
595595

596596
void onNewCameraSelected(CameraDescription cameraDescription) async {
597-
if (controller != null) {
598-
await controller!.dispose();
599-
}
597+
final previousCameraController = controller;
598+
600599
final CameraController cameraController = CameraController(
601600
cameraDescription,
602601
ResolutionPreset.medium,
603602
enableAudio: enableAudio,
604603
imageFormatGroup: ImageFormatGroup.jpeg,
605604
);
605+
606606
controller = cameraController;
607607

608+
if (mounted) {
609+
setState(() {});
610+
}
611+
608612
// If the controller is updated then update the UI.
609613
cameraController.addListener(() {
610614
if (mounted) setState(() {});
@@ -637,6 +641,8 @@ class _CameraExampleHomeState extends State<CameraExampleHome>
637641
if (mounted) {
638642
setState(() {});
639643
}
644+
645+
await previousCameraController?.dispose();
640646
}
641647

642648
void onTakePictureButtonPressed() {

0 commit comments

Comments
 (0)