在 flutter 中调整容器大小以精确到屏幕大小的一半

Sizing a container to exact half the screen size in flutter

我试图让容器恰好是屏幕高度的一半[在考虑 AppBar 高度之后] 和屏幕宽度的一半。

这是我想出的...

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Flexible(
            child: Container(
              width: MediaQuery.of(context).size.width / 2,
              color: Colors.red,
            ),
          ),
          Flexible(
            flex: 1,
            child: Container(),
          )
        ],
      ),
    );
  }
}

有没有更好的方法?

您在使用 MediaQuery 方面走在正确的轨道上,但您的代码可以简单得多:

  Scaffold(
    appBar: AppBar(),
    body: Align(
      alignment: Alignment.topCenter,
      child: Container(
        height: MediaQuery.of(context).size.height / 2,
        width: MediaQuery.of(context).size.width / 2,
        color: Colors.red,
      ),
    ),
  );

如果您希望容器的高度为可用高度的一半space,您可以使用 LayoutBuilder 小部件。使用 LayoutBuilder 小部件,您可以在构建器函数内部知道最大可用宽度和高度是多少。您的示例用法如下:

Scaffold(
      appBar: AppBar(),
      body: Align(
        alignment: Alignment.topCenter,
        child: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            return Container(
              height: constraints.maxHeight / 2,
              width: MediaQuery.of(context).size.width / 2,
              color: Colors.red,
            );
          },
        ),
      ),
    );

可以扣除AppBar的身高来配置Container的尺寸。

@override
Widget build(BuildContext context) {
  var appBar = AppBar();
  return Scaffold(
    appBar: appBar,
    body: Align(
      alignment: Alignment.topCenter,
      child: Container(
        height: (MediaQuery.of(context).size.height - appBar.preferredSize.height) / 2,
        width: MediaQuery.of(context).size.width / 2,
        color: Colors.red,
      ),
    ),
  );
}

解决此问题和类似问题的最佳方法和最简单的途径就是使用 FractionallySizedBox 小部件;例如

FractionallySizedBox(
    alignment: Alignment.topCenter,
    widthFactor: 0.5,
    child: Container(
    height: 100,
  ),
),

此小部件 (FractionallySizedBox) 允许您通过指定 child 小部件可用的父宽度(或高度)的分数来构建您的 child。之后,通过指定 alignment,您可以指定分配 space 其余部分的方式。

有关此小部件的更多帮助,请访问 offical help page of this widget

或者只是简单地...

SizedBox(
          height: MediaQuery.of(context).size.height*0.5,
          child: ...,
        ),