How to change screen orientation in flutter ?

Screen orientation plays a vital role in displaying the User Interface (UI) of different mobile apps according to their nature. An app can either be displayed in portrait mode or landscape mode.

Some mobile apps may only need landscape mode for example: in mobile games, some may need only portrait mode but some may need both the screen orientations to display.

so, these orientations may either impose restrictions or provide flexibility to the app for better user experiences.

1. Setting Screen Orientation

In order to set device orientation, we will have to import services package from flutter.

import 'package:flutter/services.dart';

Now, In the main() method, add the following code:

WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
    .then((_) {
      runApp(new MyApp());
    });

Now, lets understand the above code.

WidgetsFlutterBinding.ensureInitialized(): You only need to call this method if you need the binding to be initialized before calling runApp.

SetPreferredOrientations() : This method is used to set the device orientation, which belongs to the SystemChrome class. If you notice above, we are using then because setpreferredOrientations returns Future object. So, before calling to runApp, we will have to wait until it return the preferred screen orientation(s).

1.1 Setting to Portrait Mode Only

We can set the device orientation to portrait mode only by passing the following arguments to the setPreferredOrientations method.

SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown,DeviceOrientation.portraitUp])

1.2 Setting to Landscape Mode Only

We can also set the device orientation to landscape mode only by passing the following arguments to the setPreferredOrientations method.

SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft,DeviceOrientation.landscapeRight])

2. Getting the screen orientation

Once we have set the device screen orientation, we can also get the screen orientation to perform some actions on it.

MediaQuery.of(context).orientation

2.1 Comparing orientation programmatically

We can also compare the current screen orientation programatically as:

MediaQuery.of(context).orientation == Orientation.portrait

Happy Coding! 🙂