如何根据父级的大小布局小部件? [英] How can I layout widgets based on the size of the parent?

查看:20
本文介绍了如何根据父级的大小布局小部件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个可能具有可变大小的父小部件.

Let's say you have a parent widget that might have a variable size.

例如:

var container = new Container(
   height: 200.0, // Imagine this might change
   width: 200.0, // Imagine this might change
   // Imagine content in this container will 
   // depend on the parent container
   child: new Container(), 
);

也许你想让父容器的子容器根据它给定的大小呈现不同的东西.

And maybe you want to have the child of the parent container render something different based on the size that it's given.

考虑响应式设计断点,如果宽度超过 X 使用此布局,如果宽度低于 X 使用该布局.

在 Flutter 中最好的方法是什么?

What's the best way to do this in Flutter?

推荐答案

你会想要使用 LayoutBuilder 小部件将在布局时构建并提供父小部件的约束.

You will want to use the LayoutBuilder widget which will build at layout time and provides the parent widget's constraints.

LayoutBuilder 采用 build() 函数,该函数具有标准的 BuildContext 以及 BoxConstraints 作为可用于帮助根据大小动态呈现小部件的参数.

The LayoutBuilder takes in a build() function which has the the standard BuildContext along with the BoxConstraints as parameters that can be used to help dynamically render widgets based on size.

让我们构建一个简单的小部件示例,如果父宽度大于 200 像素,则呈现LARGE",如果父宽度小于或等于该宽度,则呈现SMALL".

Let's build a simple example of widget that renders "LARGE" if the parent width is greater than 200px and "SMALL" if the parent width is less or equal to that.

var container = new Container(
  // Toggling width from 100 to 300 will change what is rendered
  // in the child container
  width: 100.0,
  // width: 300.0
  child: new LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints) {
      if(constraints.maxWidth > 200.0) {
        return new Text('BIG');
      } else {
        return new Text('SMALL');
      }
    }
  ),
);

这篇关于如何根据父级的大小布局小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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