How to set the Device Orientation in Flutter?

In Flutter, we can set the orientation for our app using the DeviceOrientation enum.

There are 4types of Orientation we can use:

  1. portraitUp (Vertically)
  2. portraitDown (Vertically reverse)
  3. landscapeLeft (Horizontally)
  4. landscapeRight (Horizontally reverse)

Lock the orientation in portraitUp mode

We have an app that by default supports all the orientations, we want it to support only portraitUp mode so that when the screen is rotated our app remains in portraitUp mode only and not in landscapeLeft mode.

Code

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]);
  runApp(const MyApp());
}

WidgetsFlutterBinding is a class that binds the framework to the flutter engine. We need to initialise the binding before the runApp cause its necessary for the orientation setup.

In the main() method, call SystemChrome.setPreferredOrientations() with the list of preferred orientations that you want your app to support.

We can pass multiple orientations there, like both portraitUp and portraitDown.

The setPreferredOrientations method returns a Future instance, so inorder to avoid unexpected output we can keep the runApp inside the .then method

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
  ]).then((value){
	  runApp(const MyApp());
  });
}

Thanks for reading the post 🎉