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

How to detect orientation change in layout in Flutter?

1个答案

1

Detecting orientation changes (portrait or landscape) in Flutter typically involves monitoring changes in MediaQuery. MediaQuery allows us to obtain information about the current media (such as the screen), including the device's orientation.

First, ensure that your Flutter application includes MaterialApp, WidgetsApp, or CupertinoApp. These application frameworks include a MediaQuery by default.

Here is a simple example demonstrating how to detect and respond to orientation changes:

dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Orientation Demo', home: OrientationList(), ); } } class OrientationList extends StatelessWidget { Widget build(BuildContext context) { // Get the current orientation var orientation = MediaQuery.of(context).orientation; return Scaffold( appBar: AppBar( title: Text('Orientation Demo'), ), body: Center( child: Builder( builder: (context) { // Adjust UI based on orientation changes if (orientation == Orientation.portrait) { return Text('Portrait mode'); } else { return Text('Landscape mode'); } }, ), ), ); } }

In this example, OrientationList is a stateless widget that retrieves the current screen orientation using MediaQuery.of(context).orientation. It then updates the displayed text based on the current orientation within the Builder widget. When you rotate the device, Flutter rebuilds the UI, and MediaQuery.of(context).orientation returns the new orientation, causing the UI to update accordingly.

This approach is a straightforward and efficient way to handle orientation changes in Flutter. You can adjust layouts, control sizes, and more based on this orientation change to provide a better user experience.

2024年7月19日 10:55 回复

你的答案