Device Orientation

  1. Lock rotation in the entire app
  2. Quite often an application is developed only for single orientation, for example — portrait. But by default an application changes orientation when you rotate a device.

    To change this behaviour we need to explicitly define supported orientation.

    void main() {

      WidgetsFlutterBinding.ensureInitialized();

      SystemChrome.setPreferredOrientations(

              //1. Portrait mode:

              // [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]

              //2. Landscape mode:

              [DeviceOrientation.landscapeLeftDeviceOrientation.landscapeRight])

          .then((_) => runApp(const MyApp()));

    }




    Note:

    There are a small problem which is the application changes orientation after the launch :

    To solve this problem check this Article on Medium.



  3. Detect Orientation Change in Layout
  4. Now we can use MediaQuery to check orientation:

        Scaffold(

            appBarAppBar(titleconst Text('Device Orientation')),

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

                ? Container(

                    alignmentAlignment.center,

                    marginconst EdgeInsets.all(20),

                    height200,

                    colorColors.blueAccent,

                    childconst Text(

                      'Portrait Screen',

                      styleTextStyle(

                        fontSize20,

                        fontWeightFontWeight.bold,

                        colorColors.white,

                      ),

                    ),

                  )

                : Container(

                    alignmentAlignment.center,

                    marginconst EdgeInsets.all(20),

                    height200,

                    colorColors.deepOrange,

                    childconst Text(

                      'Landscape Screen',

                      styleTextStyle(

                        fontSize20,

                        fontWeightFontWeight.bold,

                        colorColors.white,

                      ),

                    ),

                  ))




    Portrait Orientation Flutter

    Landscape Orientation Flutter