Bug on Flutter's camera package when changing the phone's orientation

Bug on Flutter's camera package when changing the phone's orientation

I integrated camera package from pub.dev to use it in a Container widget on home screen on my app. The app is designed for portrait up btw.

The problem is that when rotating the phone to the horizontal orientation (I am testing on iPhone 11) the camera preview tries to be horizontal. But, the app supports only vertical orientations which causes the displayed image broken like it is too stretched in the container.

My code to initialize the camera controller is like following:

/// Initialize the camera.
  Future<void> initializeCamera() async {
    await controller?.dispose();
    _cameraException = null;
    controller = CameraController(
      _cameras[_currentCameraIndex],
      ResolutionPreset.max,
      enableAudio: false,
    );
    await controller!
        .initialize()
        .then((value) {
          // Camera initialized successfully.
          notifyListeners();
        })
        .catchError((Object e) {
          if (e is CameraException) {
            switch (e.code) {
              case 'CameraAccessDeniedWithoutPrompt':
              case 'CameraAccessDenied':
                cameraException = AppCameraException.cameraAccessDenied;
              case 'AudioAccessDenied':
              case 'AudioAccessDeniedWithoutPrompt':
                cameraException = AppCameraException.audioAccessDenied;
              default:
                cameraException = AppCameraException.unknown;
            }
          }
        });
  }

Answer

The solution is to call

await controller!.lockCaptureOrientation(DeviceOrientation.portraitUp);

But it is important to call lockCaptureOrientation after initializing the camera controller.

await controller!.initialize()
...
// After initializing the controller call .lockCaptureOrientation()
await controller!.lockCaptureOrientation(DeviceOrientation.portraitUp);

Otherwise it doesn't work.

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles