Screen Orientation In Flutter


In this tutorial, we will see all possible options to set the device orientation in Flutter

How to set the device Orientation in Flutter

First you need to import the services.dart package to access “SystemChrome” object.

SystemChrome : Controls specific aspects of the operating system’s graphical interface and how it interacts with the application. SystemChrome can not be instantiated and extended.

setPreferredOrientations : Specifies the set of orientations the application interface can  be displayed in.  The `orientation` argument is a list of [DeviceOrientation] enum values. 

The empty list causes the application to defer to the operating system  default.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations(<DeviceOrientation>[
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight
  ]).then((_) => runApp(MyApp()));
}

Enable Landscape Orientation

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations(<DeviceOrientation>[
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight
  ]).then((_) => runApp(MyApp()));
}

Enable Portrait Orientation

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SystemChrome.setPreferredOrientations(<DeviceOrientation>[
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
    ]).then((_) => runApp(MyApp()));
}

How to get the device orientation in Flutter

MediaQuery object holds the information related to current device orientation

    Orientation deviceOrientationMode = MediaQuery.of(context).orientation;

if (MediaQuery.of(context).orientation == Orientation.landscape) {
      print("Device is in landscape mode");
 } else {
       print("Device is in Portraint mode");
  }

One thought on “Screen Orientation In Flutter”

Leave a Reply

Your email address will not be published. Required fields are marked *