乐闻世界logo
搜索文章和话题

How to Detect Orientation Changes in Flutter Layout?

2月7日 11:13

In Flutter, detecting orientation changes in the layout (i.e., whether the screen is in landscape or portrait mode) can be done as follows:

  1. Using the MediaQuery object: MediaQuery.of(context) retrieves the current media query data, which includes orientation information.

  2. Retrieving orientation information: Use MediaQuery.of(context).orientation to get the current orientation. This property returns an Orientation value, which can be Orientation.landscape (landscape mode) or Orientation.portrait (portrait mode).

  3. Using setState: In the build method or other appropriate locations, use setState to update the UI when orientation changes occur.

  4. Example code:

dart
import '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.

标签:Dart