我正在寻找一种监听手机方向变化的方法,目的是在手机横向时隐藏某些内容。
我的布局目前仅按预期以纵向显示,但我希望我的应用程序在设备旋转到横向时执行某些操作,同时保持纵向布局。
我尝试过使用OrientationBuilder
,但这仅在布局更改为横向时才有效。
我也尝试过使用MediaQuery.of(context).orientation
,但一旦设备旋转,它就会继续返回纵向,同样仅使用布局方向。
您可以听到屏幕尺寸的变化,但是MediaQuery.of(...)
应该也可以工作,并且当方向改变时应该重建你的小部件
https://stephenmann.io/post/listening-to-device-rotations-in-flutter/ 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');
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)