Open In App

How to Change Screen Orientation in Flutter on Click of a Button?

Last Updated : 14 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Flutter is an open-source UI toolkit developed and maintained by Google. It is used by big companies like Airbnb, Alibaba, and Google itself to serve billions of users around the globe. While developing the UX of an application, there are many situations where you want the device to be in a specific orientation for a better user experience. In this article, we will see how to change the screen orientation to portrait or landscape. A sample video is given below to get an idea about what we are going to do in this article.

Approach

To change the orientation of the screen, we will use SystemChrome.setPreferredOrientations Method with the desired orientation as the only parameter.

Syntax

SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);

Implementation

The below example shows the use of the method discussed above to toggle the screen orientation between portraitUp and landscapeLeft.

Dart




import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
  
void main() {
    runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
    const MyApp({super.key});
  
    @override
    Widget build(BuildContext context) {
        return  MaterialApp(
            title: 'GFG - Toggle Screen Orientation',
            theme: ThemeData(primarySwatch: Colors.green),
            home: const ChangeScreenOrientation(),
        );
    }
}
  
class ChangeScreenOrientation extends StatelessWidget {
    const ChangeScreenOrientation({super.key});
  
    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
                title: const Text('GFG - Toggle Screen Orientation'),
            ),
            body: Center(
                child: ElevatedButton(
                    onPressed: () {
                        if(MediaQuery.of(context).orientation == Orientation.portrait)
                        {
                            SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
                        }else {
                            SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
                        }
                    },
                    child: const Text('Toggle Orientation'),
                ),
            ),
        );
    }
}


Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads