如何在Flutter中实现相对于屏幕尺寸的小部件大小?

5

我正在开发一个Flutter应用程序。在其中,我创建了一个SliverAppBar:

child: NestedScrollView (
  headerSliverBuilder: (BuildContext context, i) {
    return <Widget> [
      SliverAppBar (
        backgroundColor: Colors.black,
        expandedHeight: 150.0,
      )
    ];
  },

我将高度设置为150.0像素。但是我意识到这个尺寸在不同的设备上会改变。如何使尺寸在每个设备上占据屏幕的40%?


使用媒体查询获取屏幕尺寸 - https://docs.flutter.io/flutter/widgets/MediaQueryData/size.html - anmol.majhail
1个回答

3

您可以使用 BuildContext contextMediaQuery 来获取当前设备的屏幕尺寸。例如:

    var width = MediaQuery.of(context).size.width  * 0.4; // set width to 40% of the screen width
    var height = MediaQuery.of(context).size.height  * 0.4; // set height to 40% of the screen height

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接