是否有一种简单的(非layoutbuilder)方法来相对于屏幕大小(宽/高)来调整元素的大小?例如:我如何设置CardView的宽度为屏幕宽度的65%。

它不能在构建方法内部完成(显然),所以它必须推迟到构建后。是否有一个更好的地方来放置这样的逻辑?


当前回答

代码:

MediaQuery.of(context).size.width //to get the width of screen
MediaQuery.of(context).size.height //to get height of screen

其他回答

您可以构建具有Flexible或Expanded子元素的列/行,这些子元素的flex值加起来等于您想要的百分比。

您可能还会发现AspectRatio小部件很有用。

有几种可能性:

1-第一个是使用MediaQuery:

代码:

MediaQuery.of(context).size.width //to get the width of screen
MediaQuery.of(context).size.height //to get height of screen

使用示例:

Container(
        color: Colors.yellow,
        height: MediaQuery.of(context).size.height * 0.65,
        width: MediaQuery.of(context).size.width,
      )

输出:

2-使用FractionallySizedBox

创建一个小部件,将其子部件的大小设置为总可用空间的一小部分。

例子:

FractionallySizedBox(
           widthFactor: 0.65, // between 0 and 1 
           heightFactor: 1.0,
           child:Container(color: Colors.red
           ,),
         )

输出:

3-使用其他小部件,如Expanded, Flexible和AspectRatio等。

MediaQuery.of(context).size.width

使用LayoutBuilder小部件,它将为您提供约束,您可以使用这些约束来获得不包括AppBar和填充的高度。然后使用sizebox并使用来自LayoutBuilder的约束提供宽度和高度

return LayoutBuilder(builder: (context2, constraints) {
  return Column(
    children: <Widget>[
      SizedBox(
        width: constraints.maxWidth,
        height: constraints.maxHeight,
        ...

您可以将MediaQuery与小部件的当前上下文一起使用,并像这样获得宽度或高度 double width = MediaQuery.of(context).size.width double height = MediaQuery.of(context).size.height 然后,你可以把它乘以你想要的百分比