我在Container
中有两个Column
小部件,每个小部件包含一个Text
小部件。我希望文本最短的Container
扩展为匹配包含较长文本的其他容器的宽度。具有较长文本的容器应包装Text
小部件及其填充。
如果不使用容器上的固定宽度,我将无法使其工作:
return Column(
mainAxisSize: MainAxisSize.min,
children: [
// This container has a shorter text than its sibling, so it should expand
// its width to match its sibling/parent
Container(
alignment: Alignment.center,
width: 50, // I don't want this fixed width
decoration: BoxDecoration(color: Colors.orange, borderRadius: BorderRadius.only(topLeft: Radius.circular(4), topRight: Radius.circular(4))),
child: Padding(
padding: const EdgeInsets.fromLTRB(8,4,8,4),
child: Text('short'),
)
),
// This container has a longer text, so it should decide the width of the
// other container (and of the parent Column)
Container(
alignment: Alignment.center,
width: 50, // I don't want this fixed width
decoration: BoxDecoration(color: Colors.orange, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(4), bottomRight: Radius.circular(4))),
child: Padding(
padding: const EdgeInsets.fromLTRB(8,4,8,4),
child: Text('long text here'),
)
),
]
);
我尝试了几种解决方法,涉及Expanded
和Flexible
,但它们都导致“红色死亡屏”(或至少是“烦恼”)。
编辑
请明确说明-我希望Column
仅包装其内容,即将其宽度调整为容器的宽度。总而言之-除了文本最短的容器,其他所有内容都应尽可能地窄,而与其同级(文本较长的容器)一样宽。
答案 0 :(得分:2)
我在评论中看到您的小提琴。而您需要的是IntrinsicWidth
。
IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// This container has a shorter text than its sibling, so it should expand
// its width to match its sibling/parent
Padding(
padding: const EdgeInsets.symmetric(vertical: 1.0),
child: Container(
color: Colors.orange,
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
child: Text(
'short',
textAlign: TextAlign.center,
),
),
),
),
// This container has a longer text, so it should decide the width of the
// other container (and of the parent Column)
Padding(
padding: const EdgeInsets.symmetric(vertical: 1.0),
child: Container(
color: Colors.orange,
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
child: Text(
'long text here',
textAlign: TextAlign.center,
),
),
),
),
],
),
),
答案 1 :(得分:1)
您可以使用类似的方法来占据小部件的整个宽度(确保位于MaterialApp和脚手架/材料子代(家中)内
incoming, forwarding & outgoing traffic
“对齐”不是必需的,它只是为了展示宽度实际上如何与“ double.infinity”一起使用,并将文本移到其右下或右上部分。
答案 2 :(得分:0)
您可以使用Align
小部件来完成此操作。
Column(
mainAxisSize: MainAxisSize.min
children: [
Align(
alignment: Alignment.centerLeft,
child: Container(
decoration: BoxDecoration(color: Colors.orange, borderRadius: BorderRadius.only(topLeft: Radius.circular(4), topRight: Radius.circular(4))),
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
child: Text('short'),
),
),
),
Align(
alignment: Alignment.centerLeft,
child: Container(
decoration: BoxDecoration(color: Colors.orange, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(4), bottomRight: Radius.circular(4))),
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
child: Text('long text here'),
),
),
),
],
),