当父widget及其子widget想要两种不同的尺寸时,且父widget不知道如何将其子widget与其边界对时齐会发生这种情况;
以下代码未提供足够的信息来说明如何在蓝色框内对齐红色框:
Container(
color: Colors.blue,
width: 42,
height: 42,
child: Container(
color: Colors.red,
width: 24,
height: 24,
),
),
所以以下两种对齐方式都符合条件,或者其他对齐方式


在那种情况下,由于Flutter不知道如何对齐红色框,因此它将采用更简单的解决方案:不对齐红色框,并强制它占用所有可用空间; 这导致:

要解决此问题,解决方案是明确告诉Flutter如何在其父边界内对齐子项。
最常见的解决方案是将子项包装到Align
窗口小部件中:
Container(
color: Colors.blue,
width: 42,
height: 42,
child: Align(
alignment: Alignment.center,
child: Container(
color: Colors.red,
width: 24,
height: 24,
),
),
),
或
Container(
color: Colors.blue,
alignment: Alignment.center,
width: 42,
height: 42,
child: Container(
color: Colors.red,
width: 24,
height: 24,
),
),
某些小部件例如Container
或Stack
将提供alignment
属性以实现类似的行为。
网友评论