调整容器大小,使其恰好是屏幕大小的一半(颤动) [英] Sizing a container to exact half the screen size in flutter

查看:92
本文介绍了调整容器大小,使其恰好是屏幕大小的一半(颤动)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使一个容器正好是屏幕高度的一半(考虑到AppBar的高度之后)和屏幕宽度的一半.

I am trying to get a container to be exactly half the screen height[after considering the AppBar height] and half the screen width.

这就是我想出的...

This is what I came up with...

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(),
          )
        ],
      ),
    );
  }
}

有更好的方法吗?

推荐答案

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

If you want the container's height to be the half of the available space, you can use LayoutBuilder widget. With LayoutBuilder widget, you can know inside the builder function what the max available width and height would be. The example usage in your case would be like this:

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,
            );
          },
        ),
      ),
    );

这篇关于调整容器大小,使其恰好是屏幕大小的一半(颤动)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆