调整容器大小,使其恰好为屏幕颤动的一半

时间:2019-01-12 02:46:44

标签: flutter flutter-layout

我正在尝试使一个容器正好是屏幕高度的一半(考虑到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(),
          )
        ],
      ),
    );
  }
}

有更好的方法吗? current layout

4 个答案:

答案 0 :(得分:5)

您在使用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,
      ),
    ),
  );

答案 1 :(得分:3)

如果希望容器的高度为可用空间的一半,则可以使用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,
            );
          },
        ),
      ),
    );

答案 2 :(得分:3)

您可以扣除chcp 65001 test.exe 的高度来配置AppBar的大小。

Container

enter image description here

答案 3 :(得分:2)

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

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

此小部件(FractionallySizedBox)可让您通过指定child小部件可用的父级宽度(或高度)的一部分来构建child。然后,通过指定alignment,可以指定剩余空间的分配方式。

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