如何根据设备方向为属性设置不同的值



我想根据屏幕方向改变Positioned小部件的top属性值。

我不知道该怎么做。

有人能帮忙吗?

userMediaQuery.of(context).orientation
可以响应设备的方向

Positioned(
top: MediaQuery.of(context).orientation == Orientation.portrait ? portraitValue : landScapeValue,
child: //your code
);

根据官方的flutter文章,您可以使用OrientationBuilder来管理基于设备方向的小部件,如下所示:

OrientationBuilder(
builder: (context, orientation) {
return Positioned(
top: orientation == Orientation.portrait ? 10 : 50,
child: /*...0*/
);
},
),

更改1050的值。

如果你愿意在其他地方获取设备的方向而不是在你的应用中的小部件,比如方法,你可以使用MediaQuery.of(context).orientation来获取设备的实际方向

printOrientation() {
print(MediaQuery.of(context).orientation);
}

查看更多信息:

OrientationBuilder ()

MediaQuery.of(上下文).orientation

最新更新