Flutter: How to set and lock screen orientation on-demand

Jus10 picture Jus10 · May 14, 2018 · Viewed 55.5k times · Source

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.

Answer

Jus10 picture Jus10 · May 14, 2018

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();
}