174

On one of my flutter pages, I need the screen to set to landscape mode and lock it so it can't rotate into portrait mode, but only on the one page. So need a way to enable this function on-the-fly. Anyone know how to do this?

I would like it to rotate landscape-left or landscape-right, just not into portrait mode.

14 Answers 14

303

First import the services package:

import 'package:flutter/services.dart';

This will give you access to the SystemChrome class, which "Controls specific aspects of the operating system's graphical interface and how it interacts with the application."

When you load the Widget, do something like this:

@override
void initState(){
  super.initState();
  SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
  ]);
}

then when I leave the page, put it back to normal like this:

@override
dispose(){
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeRight,
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
  super.dispose();
}
10
44

I would use a simple mixin to lock phone in portrait. The following solution locks the entire app in portrait or sets specific screens to portrait while keeping rotation elsewere.

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

/// Forces portrait-only mode application-wide
/// Use this Mixin on the main app widget i.e. app.dart
/// Flutter's 'App' has to extend Stateless widget.
///
/// Call `super.build(context)` in the main build() method
/// to enable portrait only mode
mixin PortraitModeMixin on StatelessWidget {
  @override
  Widget build(BuildContext context) {
    _portraitModeOnly();
    return null;
  }
}

/// Forces portrait-only mode on a specific screen
/// Use this Mixin in the specific screen you want to
/// block to portrait only mode.
///
/// Call `super.build(context)` in the State's build() method
/// and `super.dispose();` in the State's dispose() method
mixin PortraitStatefulModeMixin<T extends StatefulWidget> on State<T> {
  @override
  Widget build(BuildContext context) {
    _portraitModeOnly();
    return null;
  }

  @override
  void dispose() {
    _enableRotation();
    super.dispose();
  }
}

/// blocks rotation; sets orientation to: portrait
void _portraitModeOnly() {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
}

void _enableRotation() {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight,
  ]);
}

To block rotation in the entire app implement PortraitModeMixin in the main App widget. Remember to call super.build(context) in Widget build(BuildContext context) method.

/// Main App widget
class App extends StatelessWidget with PortraitModeMixin {
  const App();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return CupertinoApp(
      title: 'Flutter Demo',
      theme: CupertinoThemeData(),
      home: Text("Block screen rotation example"),
    );
  }
}

To block rotation in a specific screen implement PortraitStatefulModeMixin<SampleScreen> in the specific screen's state. Remember to call super.build(context) in the State's build() method and super.dispose() in dispose() method. If your screen is a StatelessWidget - simply repeat the App's solution (previous example) i.e. use PortraitModeMixin.

/// Specific screen
class SampleScreen extends StatefulWidget {
  SampleScreen() : super();

  @override
  State<StatefulWidget> createState() => _SampleScreenState();
}

class _SampleScreenState extends State<SampleScreen>
    with PortraitStatefulModeMixin<SampleScreen> {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Text("Flutter - Block screen rotation example");
  }

  @override
  void dispose() {
     super.dispose();
  }
}

Mixins with such syntax work from Dart 2.1

6
  • 2
    I have tried your mixin class - stateless version works just fine, however statefull one throws an exception, once my statefull class calls its disposed method. Note, I call super.dispose() within my class. Below is the error: I/flutter (29686): The following assertion was thrown while finalizing the widget tree: I/flutter (29686): _MultiPlayerAcceptPageState.dispose failed to call super.dispose. I/flutter (29686): dispose() implementations must always call their superclass dispose() method, to ensure that all the I/flutter (29686): resources used by the widget are fully released. Mar 30, 2019 at 22:11
  • 1
    Same exception for stateful version. Did you solve this problem ?
    – cwhisperer
    Jan 7, 2020 at 13:05
  • 1
    Solved it! If you use Android Studio, this is clearly detectable. It says dispose() is annotated as @mustCallSuper. This means you need to add super.dispose() within the mixin function itself. Jan 18, 2021 at 1:01
  • return null; in the mixin throws following error: A value of type 'Null' can't be returned from the method 'build' because it has a return type of 'Widget'.
    – cwhisperer
    Apr 25, 2022 at 15:26
  • 1
    This is an awesome answer, though a little dated now. Replace return null with return super.build(context); in the newer versions of Flutter and it will work just fine. Dec 27, 2022 at 20:19
39

First, Lock the entire app orientation to Portrait mode.

//Do this in main.dart
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
  .then((_) {
runApp(MyApp());
});

Second, Go the specific screen where you want to change the orientation.

@override
void initState() {
super.initState();

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

}

@override
void dispose() {
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
super.dispose();
}

For using SystemChrome you will have to add 'package:flutter/services.dart'

4
  • 1
    what to do in case of stateless widget ?
    – p2kr
    May 23, 2021 at 11:14
  • 2
    You need a stateful widget for access to the lifecycle methods.
    – Anthony O
    Aug 4, 2021 at 18:50
  • My app normally works on portrait. When I move to LandscapeScreen from HomeScreen, I have set to landscape mode. When I press back, It Loads the HomeScreen in LandscapeScreen mode first and then build it portrait. This happens in less a second. Apr 23, 2022 at 1:01
  • no effect on iOS 16 - any ideas
    – iOS Flow
    Oct 18, 2022 at 11:05
20
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp, DeviceOrientation.portraitDown])
    .then((_) {
      runApp(new MyApp());
    });
}
1
  • 5
    While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.
    – borchvm
    May 5, 2020 at 6:51
7

import services.dart package and add following code to lock device orientation to portraitUp mode:

 import 'package:flutter/services.dart';

 main() {
     WidgetsFlutterBinding.ensureInitialized();
     SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
     runApp(MyHomePage());
 }
1
  • WidgetsFlutterBinding.ensureInitialized(); made this solution work for me. Good catch!
    – AWP
    Sep 12, 2021 at 19:44
5

Sometimes it could not work due to null info about orientation. You can use it simply like this:

import services.dart


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

// wait for settings screen orientation after initiating app and -> then lock orientation

4

Important for iOS.

  • Enable the orientation in in info.plist file. for Example enter image description here

Steps

  • Set the orientation in main.dart file. In my case, My application is only support for portrait except the one screen so i need to set the portrait mode at first time. for Example
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp,DeviceOrientation.portraitDown,]);
  • Add the following code in that screen which you need to rotate.
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
      DeviceOrientation.landscapeLeft,
    ]);
  }
  @override
  dispose(){
     SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
    super.dispose();
  }
4

Simple way to lock screen orientation in whole app

  • Add import 'package:flutter/services.dart'; to the start of main.dart file.

  • Create SystemChrome.setPreferredOrientations(); method to disable Screen rotation in Widget build area of MyApp class just before the return part.

  • Specify the orientation using [DeviceOrientation.<orientation-type>] in arguments of the method.

Use one of the following in place of <orientation-type> :

  1. portraitUp
  2. portraitDown
  3. landscapeLeft
  4. landscapeRight

Example Code:

import 'package:flutter/material.dart';
 
import 'package:flutter/services.dart' ;
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
 
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
 
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
        title: Text("Screen Orientation"),
        ),
        body: Container(
        ),
      ),
    );
  }
}
3

import services.dart and your void main function should be like:

void main(){

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

In AndroidManifest file in main folder under activity tag set android:screenOrientation = "portrait"

<activity android:windowSoftInputMode="adjustResize" android:screenOrientation = "portrait">
1

You can use orientation_helper for this https://pub.dev/packages/orientation_helper . It’s main goal is to set orientation for each screen in an app.

1

For those who prefer to use hooks

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

useOrientation(List<DeviceOrientation> orientations) {
  useEffect(
    () {
      SystemChrome.setPreferredOrientations(orientations);
      return () {
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
          DeviceOrientation.landscapeLeft,
          DeviceOrientation.landscapeRight,
        ]);
      };
    },
  );
}

Use it like:

class MyWidget extends HookWidget {
  void build(BuildContext context) {

    useOrientation([DeviceOrientation.portraitUp]);

    return Container();
  }
}
0

Set the preferred orientation in the flutter.

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

// Lock the orientation to Portrait Only
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((value) => runApp(MyApp()));

You can also add Preferred Orientations in the setPreferredOrientations list like [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]

Below are the orientation you can set:

/// If the device shows its boot logo in portrait, then the boot logo is shown
  /// in [portraitUp]. Otherwise, the device shows its boot logo in landscape
  /// and this orientation is obtained by rotating the device 90 degrees
  /// clockwise from its boot orientation.
  portraitUp,

  /// The orientation that is 90 degrees clockwise from [portraitUp].
  ///
  /// If the device shows its boot logo in landscape, then the boot logo is
  /// shown in [landscapeLeft].
  landscapeLeft,

  /// The orientation that is 180 degrees from [portraitUp].
  portraitDown,

  /// The orientation that is 90 degrees counterclockwise from [portraitUp].
  landscapeRight,

Ref: https://greymag.medium.com/flutter-orientation-lock-portrait-only-c98910ebd769

-1

In GetX, you need to use GetBuilder like this example:


    final Controller ctrl = Get.find();

    GetBuilder<Controller>(
      initState: (_) => ctrl.setLandscape(),
      dispose: (_) => ctrl.setPortrait(),
      builder: (code) => Container(
          padding: const EdgeInsets.zero,
          alignment: Alignment.Center,
          child: const SizedBox(),
       ),
    ),

In Controller file:

    class Controller extends GetxController {
      RxBool isLandscape = false.obs;

      Future<void> setLandscape() async {
        if (isLandscape.isTrue) {
          await SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
          update();
        }
      }
      
      Future<void> setPortrait() async {
        if (isLandscape.isFalse) {
          await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
          update();
        }
      }
    }

I hope this solution will answer developers who use GetX as their main state management. Good luck, bro! God blesses you all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.