Open In App

Restrict Landscape mode in Flutter

In this article, we’ll learn how to restrict landscape mode in the flutter app. A production-ready app should be free from all sorts of bugs and errors. Mostly, we design our app for portrait orientation, if we flip to landscape orientation, UI might not be adjusted for that. So, there are two cases, first is, your app can be adjusted for landscape orientation and second is that your app might not require landscape orientation. So, in the second case, we can restrict the landscape orientation. This can be done by using the default SystemChrome class. This class has a method setPreferredOrientations, which takes a list of device orientations that need to be implemented in the app. 

Available Orientations:

Syntax: SystemChrome.setPreferredOrientations([DeviceOrientation.yourChoice])

Here, SystemChrome is the default class that controls many device features. This class has method setPreferredOrientations which takes a list of type DeviceOrientation and preferred orientations can be passed to it as a list.

Example:






import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; //For using SystemChrome
  
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations(
    [DeviceOrientation.portraitUp]);
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text('This app can\'t be rotated to Landscape mode',
              style: TextStyle(color: Colors.green, 
                fontSize: 17),
          ),
        ),
      ),
    );
  }
}

Output:



The output app as shown above would be restricted to only portrait mode. Even if you rotate the device, it would not change to landscape mode. 

Points to remember:

Article Tags :