How to Listen Screen Orientation Mode Change in Flutter

In this example, we are going to show you the best way to detect or listen to the Screen Orientation mode change from Landscape to Portrait or vice versa. This kind of functionality is very important to maintain the messy UI in App. See the example below for more details.

OrientationBuilder(
  builder: (context, orientation) {
    //check orientation variable to identiy the current mode
    if(orientation == Orientation.portrait){
      print("The screen is in Portrait mode");
    }

    if(orientation == Orientation.landscape){
      print("The screen is on Landscape mode.");
    }

    return Container();
  }
)

Whenever the orientation of your screen changes, there will be an automatic UI refresh.

import 'package:flutter/material.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget{
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: Scaffold(
        appBar: AppBar(title:Text("Listen Orientation Change")),
        body: OrientationBuilder(
              builder: (context, orientation) {
                //check orientation variable to identiy the current mode
                if(orientation == Orientation.portrait){
                  print("The screen is in Portrait mode");
                }

                if(orientation == Orientation.landscape){
                  print("The screen is on Landscape mode.");
                }

                return Container(
                  height: 250,
                  color: Colors.blue.shade50,
                  child: Center(
                      child: Text(orientation == Orientation.portrait?
                                "Current Orientation is Portrait":
                                "Current Orientation is Landcape",
                                style: TextStyle(fontSize: 18),),
                  ),
                );
        }),
      )
    );
  }
}

In this way, you can listen or detect Orientation mode change in Flutter App.

No any Comments on this Article


Please Wait...