首页 > 解决方案 > Flutter 如何计算屏幕宽度

问题描述

我有一个简单的颤振设置来获取分辨率为 2960*1440 的设备上的屏幕宽度。

但是,当我以 2960*1440 分辨率运行应用程序时,颤动返回的屏幕宽度为 411。颤振如何计算设备的宽度?

class page extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width.toString();

    return Container(
      child: Text("Height : $height and Width : $width"),

    );
  }
}

标签: flutter

解决方案


颤振取决于MediaQuery计算屏幕尺寸的方法:

  MediaQuery.of(context).size.width ;

根据文档 ,它返回屏幕的“逻辑像素”的数量,其中每个像素代表几个物理像素,因设备而异,如果您想要实际的像素数,可以使用:

  MediaQuery.of(context).size.width * MediaQuery.of(context).devicePixelRatio ;

对于屏幕高度的实际像素:

  MediaQuery.of(context).size.height * MediaQuery.of(context).devicePixelRatio ;

推荐阅读