Flutter:约束不约束小部件(需要解释) [英] Flutter: Constraints not constraining widget (explanation needed)

查看:243
本文介绍了Flutter:约束不约束小部件(需要解释)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类测试扩展了StatelessWidget {
Widget build(BuildContext context){
return UnconstrainedBox(
child:Container(
height:250.0 ,
宽度:250.0,
装饰:
BoxDecoration(形状:BoxShape.circle,颜色:Colors.red),
子级:不透明度(
透明度:0.5,
child:Container(//问题中的
约束条件:
BoxConstraints.expand(width:50.0,height:50.0),
color:Colors.yellow))))​​);
}
}

根据



当前获得:

解决方案

问题出在您的根容器上。



通过设置宽度+高度设置对齐方式,Container会强制其子级填充可用空间。



如果您希望该子级占用最少的空间,则需要指定根容器,以使其在子级内对齐子级。

 容器(
宽度:250,
高度:250,
对齐方式:Alignment.center,
子级:Whatever(),
);


class Test extends StatelessWidget {
  Widget build(BuildContext context) {
    return UnconstrainedBox(
        child: Container(
            height: 250.0,
            width: 250.0,
            decoration:
                BoxDecoration(shape: BoxShape.circle, color: Colors.red),
            child: Opacity(
                opacity: 0.5,
                child: Container( // WIDGET IN QUESTION
                    constraints:
                        BoxConstraints.expand(width: 50.0, height: 50.0),
                    color: Colors.yellow))));
  }
}

According to the Container class documentation...

If the widget has no child and no alignment, but a height, width, or constraints are provided, then the Container tries to be as small as possible given the combination of those constraints and the parent's constraints.

Instead, the widget is trying to be as large as possible (size of parent) rather than 50x50. I understand that I can use something like UnconstrainedBox, but I'm looking for an explanation of this behavior.

Looking for:

Currently getting:

解决方案

The problem is your root Container.

By setting a width+height without an alignment, Container forces its child to fill the available space.

If you want that child take the least amount of space, you need to specify your root container how it should align its child within its bounds.

Container(
  width: 250,
  height: 250,
  alignment: Alignment.center,
  child: Whatever(),
);

这篇关于Flutter:约束不约束小部件(需要解释)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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