聆听Flutter中设备方向的变化 [英] Listening For Device Orientation Changes In Flutter
问题描述
我正在寻找一种监听手机方向变化的方法,目的是在手机为风景手机时隐藏某些东西.
I am looking for a way of listening for changes to the phones orientation, with the intent to hide something if the phone is Landscape.
我的布局"目前仅按预期显示为纵向,但是我希望我的应用程序在设备旋转到横向"的同时将布局保持为纵向".
My Layout is currently only displayed in portrait, as intended, but I want my app to do something if the device is rotated to Landscape, while keeping the layout in Portrait.
我尝试使用 OrientationBuilder
,但这仅在布局更改为横向"时有效.
I have tried using a OrientationBuilder
, but this only works if the layout changes to Landscape.
我也尝试过使用 MediaQuery.of(context).orientation
,但是一旦旋转设备,它将继续返回纵向,同样仅使用布局方向.
I have also tried using MediaQuery.of(context).orientation
, but it continues to return portrait once the device is rotated, again only using the layouts orientation.
推荐答案
您可以听取屏幕尺寸的变化,但是 MediaQuery.of(...)
应该也可以工作,并且应该重建方向改变时您的窗口小部件
You can listen to screen size changes, but MediaQuery.of(...)
should work as well and should cause rebuilds of your widget when orientation changes
https://stephenmann.io/post/listening-to-device-rotations-in-flutter/
import 'dart:ui';
import 'package:flutter/material.dart';
class WidthHeight extends StatefulWidget {
WidthHeight({ Key key }) : super(key: key);
@override
WidthHeightState createState() => new WidthHeightState();
}
class WidthHeightState extends State
with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
double width = 0.0;
double height = 0.0;
@override void didChangeMetrics() {
setState(() {
width = window.physicalSize.width;
height = window.physicalSize.height;
});
}
@override
Widget build(BuildContext context) {
return new Text('Width: $width, Height $height');
}
}
这篇关于聆听Flutter中设备方向的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!