問題描述
想要實(shí)現(xiàn)一個(gè)大 Container嵌套一個(gè)小 Container 的布局,如下圖所示

希望的效果
///代碼
Container(
width: 200,
height: 200,
color: Colors.red,
child: Container(
width: 50,
height: 50,
color: Colors.blue,
),
)
但是運(yùn)行結(jié)果確實(shí)下圖效果
代碼運(yùn)行結(jié)果
問題探究
先看下解決辦法
///增加個(gè)對(duì)齊方式
Container(
width: 200,
height: 200,
color: Colors.red,
alignment: Alignment.center,///增加個(gè)對(duì)齊方式
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的代碼實(shí)現(xiàn)吧 , 其關(guān)鍵在于一個(gè)屬性 : 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不是一個(gè)必傳的參數(shù),但是呢,會(huì)為我們?cè)O(shè)置一個(gè)默認(rèn)值,而其生效條件是這么判斷的
如果寬高為空怎選擇默認(rèn)值,如果寬高不為空但是不滿足默認(rèn)值條件則選擇默認(rèn)值, BoxConstraints 里的默認(rèn)寬高是屏幕寬高.
///BoxConstraints的初始設(shè)置
const BoxConstraints.tightFor({
double? width,
double? height,
}) : minWidth = width ?? 0.0,
maxWidth = width ?? double.infinity,
minHeight = height ?? 0.0,
maxHeight = height ?? double.infinity;