问题描述
想要实现一个大 Container嵌套一个小 Container 的布局,如下图所示
///代码
Container(
width: 200,
height: 200,
color: Colors.red,
child: Container(
width: 50,
height: 50,
color: Colors.blue,
),
)
但是运行结果确实下图效果问题探究
先看下解决办法
///增加个对齐方式
Container(
width: 200,
height: 200,
color: Colors.red,
alignment: Alignment.center,///增加个对齐方式
child: Container(
width: 50,
height: 50,
color: Colors.blue,
),
)
///或者包一层row,column,center
Container(
width: 200,
height: 200,
color: Colors.red,
child: Center(
child: Container(
width: 50,
height: 50,
color: Colors.blue,
),
),
)
那么问题来了 , 为什么同样是容器 , Container差在哪里了呢 ? 那我们来看下Container的代码实现吧 , 其关键在于一个属性 : BoxConstraints .
Container({
Key? key,
this.alignment,
this.padding,
this.color,
this.decoration,
this.foregroundDecoration,
double? width,
double? height,
BoxConstraints? constraints,
this.margin,
this.transform,
this.transformAlignment,
this.child,
this.clipBehavior = Clip.none,
}) : assert(margin == null || margin.isNonNegative),
assert(padding == null || padding.isNonNegative),
assert(decoration == null || decoration.debugAssertIsValid()),
assert(constraints == null || constraints.debugAssertIsValid()),
assert(clipBehavior != null),
assert(decoration != null || clipBehavior == Clip.none),
assert(color == null || decoration == null,
'Cannot provide both a color and a decoration\n'
'To provide both, use "decoration: BoxDecoration(color: color)".',
),
constraints =
(width != null || height != null)
? constraints?.tighten(width: width, height: height)
?? BoxConstraints.tightFor(width: width, height: height)
: constraints,
super(key: key);
代码中可以看到BoxConstraints不是一个必传的参数,但是呢,会为我们设置一个默认值,而其生效条件是这么判断的
如果宽高为空怎选择默认值,如果宽高不为空但是不满足默认值条件则选择默认值, BoxConstraints 里的默认宽高是屏幕宽高.
///BoxConstraints的初始设置
const BoxConstraints.tightFor({
double? width,
double? height,
}) : minWidth = width ?? 0.0,
maxWidth = width ?? double.infinity,
minHeight = height ?? 0.0,
maxHeight = height ?? double.infinity;