How to set and lock screen orientation on-demand in Flutter
In Flutter, controlling the screen orientation of your app is primarily achieved by using the class, which is part of the 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 OrientationTo set the screen orientation, you need to call the method in your app's function or the method of a page. For example, if you want your app to support only portrait mode, you can do the following:This code ensures the screen orientation is set prior to app startup, preventing unexpected screen orientation changes.How to Lock Screen OrientationLocking 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 method of the page, as shown below: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 ExampleIn 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.