Flutter How to change the Screen Orientation Dynamically

Last updated Sep 15, 2021

Usually mobile applications will develop to support for both Portrait and Landscape mode. But sometimes we may require to fix a specific mode (Only Portrait or Only Landscape). To set app orientation in flutter we will use flutter SystemChrome class.

To use this class we need to import the service.dart file

import 'package:flutter/services.dart';

 

Now we need to call the setPrefferedOrientation method on SystemChrome object. Now if we want to set orientation complete application we need to call this on entry point of the flutter application. we knows that main() is the entry point of the any flutter application, so let's add this code in main()

 

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]).then((_){
    runApp(MyApp());
  });
}

 

How to set portrait orientation only

to set Only Portrait Orientation we will use the below code

SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitDown,DeviceOrientation.portraitUp]
)

 

Change Orientation dynamically

To change the orientation dynamically we will use the below code

SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp]
);

 

Create a Material Button and add above code inside onPressed() method

MaterialButton(
  color: Colors.red,
    textColor: Colors.white,
    child: Text("Portrait"),
    onPressed: (){
      SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    })

 

Flutter Chnage Screen Orientation dynamically

 

 

Download Source code

 

 

Sample Flutter code to set Orientation dynamically

import 'package:flutter/material.dart';
import "package:flutter/services.dart";

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]).then((_){
    runApp(MyApp());
  });
}
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    print("Called");
    return Scaffold(
        appBar: AppBar(title:Text("Rotate Widget")),
        body:SingleChildScrollView(
          child: Center(
              child:Card(
                child: Column(
                  children: [
                    Image.network("https://images.unsplash.com/photo-1591969851586-adbbd4accf81?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cm9tYW50aWMlMjBjb3VwbGV8ZW58MHx8MHx8&ixlib=rb-1.2.1&w=1000&q=80",height:200,),
                    MaterialButton(
                        color: Colors.green,
                        textColor: Colors.white,
                        onPressed: (){
                          print("Called");

                        },child:Text("Play Viedo")),
                    MaterialButton(
                      color: Colors.red,
                        textColor: Colors.white,
                        child: Text("Portrait"),
                        onPressed: (){
                          SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
                        })
                  ],
                ),
              )
          ),
        )
    );
  }
}

 

 

Set Orientation of the single screen

To set a single screen of the application to a specific orientation we can use mixin class to handle the orientation

We need to extend these class for any of our widget(Stateless/Statefull widgets)

 

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 (You can change as per requirement)

mixin PortraitModeMixin on StatelessWidget {
  @override
  Widget build(BuildContext context) {
    _portraitModeOnly();
    return SizedBox.shrink();
  }
}

 

Forces portrait-only mode on a specific screen Use this Mixin in the specific screen you want to
 block to portrait only mode (You can change as per requirement).
 Call `super.build(context)` in the State's build() method and `super.dispose();` in the State's dispose() method

mixin PortraitStatefulModeMixinextends StatefulWidget> on State {
  @override
  Widget build(BuildContext context) {
    _portraitModeOnly();
    return SizedBox.shrink();
  }

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

/// 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,
  ]);
}

source

 

Conclusion: In this flutter example we learned how to set orientation of the application dynamically.

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

2943 Views