Take camera picture in landscape and portrait with rotation disabled in Flutter

Viewed 903

I want to build a screen that allows me to take photos in landscape and portrait. My app only runs in portrait mode by calling the following in main:

await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

Due to the fact that my screen doesn't rotate anymore, the images are always taken in portrait, even if I tilt the phone to the side. Here is a small example project where you can see it clearly:

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter/services.dart';

List<CameraDescription> cameras = [];

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  cameras = await availableCameras();
  runApp(CameraApp());
}

class CameraApp extends StatefulWidget {
  @override
  _CameraAppState createState() => _CameraAppState();
}

class _CameraAppState extends State<CameraApp> {
  CameraController? controller;
  bool takingPicture = false;
  XFile? selectedImage;

  @override
  void initState() {
    super.initState();
    controller = CameraController(cameras[0], ResolutionPreset.max);
    controller!.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!controller!.value.isInitialized) {
      return Container();
    }
    return MaterialApp(
      home: Stack(
        fit: StackFit.expand,
        children: [
          RotatedBox(
            quarterTurns: 1 - controller!.description.sensorOrientation ~/ 90,
            child: CameraPreview(controller!),
          ),
          CameraPreview(controller!),
          Align(
            alignment: Alignment.bottomRight,
            child: FloatingActionButton(
              onPressed: () {
                if (!takingPicture) {
                  takingPicture = true;
                  controller!.takePicture().then(
                    (value) {
                      selectedImage = value;
                      setState(() {});
                      takingPicture = false;
                    },
                  );
                }
              },
            ),
          ),
          Align(
            alignment: Alignment.bottomLeft,
            child: selectedImage != null
                ? Container(
                    height: 100,
                    width: 200,
                    child: Image.file(
                      File(selectedImage!.path),
                    ),
                  )
                : Container(),
          ),
        ],
      ),
    );
  }
}

When rotating the phone and taking a photo, the photo should also appear in Landscape, but it doesn't. How can I work around this without taking out setPreferredOrientations?

The normal mobile app on Android and iOS can do that too.

1 Answers

What I would do is to remove the constraint when entering the screen and reapplying it when entering.

Here is an example adapted from your code which features 2 screens:

  • A welcome screen which cannot rotate
  • The camera screen which does rotate
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:flutter/services.dart';

List<CameraDescription> cameras = [];

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  cameras = await availableCameras();
  runApp(MaterialApp(home: WelcomeScreen()));
}

class WelcomeScreen extends StatelessWidget {
  const WelcomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Welcome! Try rotating the screen, you won\'t be able to!'),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pushReplacement(
                MaterialPageRoute(builder: (_) => CameraApp()),
              ),
              child: Text('Press me to go to the camera'),
            ),
          ],
        ),
      ),
    );
  }
}

class CameraApp extends StatefulWidget {
  @override
  _CameraAppState createState() => _CameraAppState();
}

class _CameraAppState extends State<CameraApp> {
  CameraController? controller;
  bool takingPicture = false;
  XFile? selectedImage;

  @override
  void initState() {
    super.initState();

    // Remove the constraint when entering, this is ok
    // not to away since the app is in portrait mode by
    // default
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    controller = CameraController(cameras[0], ResolutionPreset.max);
    controller!.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!controller!.value.isInitialized) {
      return Container();
    }
    return MaterialApp(
      home: Stack(
        fit: StackFit.expand,
        children: [
          RotatedBox(
            quarterTurns: 1 - controller!.description.sensorOrientation ~/ 90,
            child: CameraPreview(controller!),
          ),
          CameraPreview(controller!),
          Align(
            alignment: Alignment.bottomCenter,
            child: ElevatedButton(
              onPressed: () async {
                // Restore the constraint before navigating away
                // DO await here to avoid any other screen in
                // landscape mode
                await SystemChrome.setPreferredOrientations([
                  DeviceOrientation.portraitUp,
                ]);

                Navigator.of(context).pushReplacement(
                  MaterialPageRoute(builder: (_) => WelcomeScreen()),
                );
              },
              child: Text('Press me to go Home'),
            ),
          ),
          Align(
            alignment: Alignment.bottomRight,
            child: FloatingActionButton(
              onPressed: () async {
                if (!takingPicture) {
                  takingPicture = true;
                  controller!.takePicture().then(
                    (value) {
                      selectedImage = value;
                      setState(() {});
                      takingPicture = false;
                    },
                  );
                }
              },
            ),
          ),
          Align(
            alignment: Alignment.bottomLeft,
            child: selectedImage != null
                ? Container(
                    height: 100,
                    width: 200,
                    child: Image.file(
                      File(selectedImage!.path),
                    ),
                  )
                : Container(),
          ),
        ],
      ),
    );
  }
}
Related