How to Detect Orientation Changes in Flutter Layout?
In Flutter, detecting orientation changes in the layout (i.e., whether the screen is in landscape or portrait mode) can be done as follows:
-
Using the
MediaQueryobject:MediaQuery.of(context)retrieves the current media query data, which includes orientation information. -
Retrieving orientation information: Use
MediaQuery.of(context).orientationto get the current orientation. This property returns anOrientationvalue, which can beOrientation.landscape(landscape mode) orOrientation.portrait(portrait mode). -
Using
setState: In thebuildmethod or other appropriate locations, usesetStateto update the UI when orientation changes occur. -
Example code:
dartimport 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: HomeScreen(), ); } } class HomeScreen extends StatefulWidget { _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { Widget build(BuildContext context) { Orientation orientation = MediaQuery.of(context).orientation; return Scaffold( appBar: AppBar( title: Text('Orientation Demo'), ), body: Center( child: orientation == Orientation.landscape ? Text('Landscape Mode') : Text('Portrait Mode'), ), ); } }
This code displays the current screen orientation in the application, and the text updates dynamically when you rotate the device.