In Flutter, controlling the screen orientation of your app is primarily achieved by using the SystemChrome class, which is part of the flutter/services.dart package. You can set the screen orientation at any point in your app, typically during app startup or when initializing a specific page.
How to Set Screen Orientation
To set the screen orientation, you need to call the SystemChrome.setPreferredOrientations() method in your app's main() function or the initState() method of a page. For example, if you want your app to support only portrait mode, you can do the following:
dartimport 'package:flutter/services.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]).then((_) { runApp(MyApp()); }); }
This code ensures the screen orientation is set prior to app startup, preventing unexpected screen orientation changes.
How to Lock Screen Orientation
Locking screen orientation typically means setting a fixed orientation for a specific page in your app. For instance, on a video playback page, you might want to lock it to landscape mode. This can be set in the initState() method of the page, as shown below:
dartvoid initState() { super.initState(); SystemChrome.setPreferredOrientations([ DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft, ]); } void dispose() { // When leaving the page, restore to a state where rotation is allowed SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft, ]); super.dispose(); }
This way, when the user enters the page, the screen automatically switches to landscape mode; when the user leaves the page, the screen orientation setting is restored to the default state, allowing free rotation.
Real-World Example
In one of my projects, we developed a media playback app where users typically prefer landscape mode while watching videos. Therefore, on the video playback page, we locked the screen to landscape mode to optimize the user experience. Simultaneously, on other pages like settings or user information, we allow free rotation for flexibility.
By doing this, we effectively control the screen orientation of the app, making the user experience more intuitive and user-friendly.