flutter - 文本溢出:有没有办法不为父级设置固定宽度?
问题描述
我想在 Flutter 中显示一个包含图片、标题和一些附加信息的元素列表。我的布局应该是这样的:
我已经使用带孩子的方法实现了这ListView
一点Card
。然后我使用 aRow
在左侧显示图像,在右侧显示信息。然后我使用 aColumn
将我的标题放在顶部,其余信息放在下面。
我的问题是标题,它可能对于其容器的宽度来说太大了。我最初的想法是让用户滚动浏览文本,但我不确定是否可以在 Flutter 中嵌套两个启用滚动的小部件,所以我决定使用TextOverflow.ellipsis
. 但是在我的基本设置TextOverflow.ellipsis
中没有任何效果,而是我面临溢出错误。
在网上查找后,我认为我必须将我Text
的放入Expanded
or Flexible
,它们本身必须是 a 的直接子代Flex
(我使用过Row
)。然而,这还不够,因为我收到以下错误:RenderFlex children have non-zero flex but incoming width constraints are unbounded.
. 为了解决这个问题,我必须添加一个具有固定宽度的( )Container
作为父级。Row
Flex
这是我当前的代码:
Card(
color: backgroundColor,
child: Row(
children: <Widget>[
MyImageWidget(),
Container(
height: 60,
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(vertical: 4, horizontal: 12),
height: 30,
width: 340, // I don't want this
child: Row(
children: [
Expanded(
child: Text(
"Title which may be long, very very long",
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
],
),
),
],
),
),
],
),
);
有没有办法摆脱这种固定宽度的限制?我知道我可以使用媒体查询,但我不想这样做,除非我绝对必须这样做,因为我可能会更改几个元素的填充,甚至移动到更大屏幕上的网格视图。
或者,如果我绝对必须设置这个固定宽度,有没有办法让 Flutter 找出Container
如果它没有内容时我的宽度是多少,然后将其应用为自身的固定宽度?
解决方案
您只需将右侧包装Column
在一个Expanded
小部件中,让它占据内部所有剩余的可用空间,其余Row
的TextOverflow.ellipsis
将处理。
return Card(
color: backgroundColor,
child: Row(
children: <Widget>[
MyImageWidget(),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 4,
horizontal: 12,
),
child: Column(
children: <Widget>[
Text(
"Title which may very very very very very very",
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
],
),
),
),
],
),
);