You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter自定义列表项文本溢出问题:TextOverflow.ellipsis不生效的解决方案

解决Flutter ListView中TextOverflow.ellipsis不生效的问题

这个问题我之前也踩过坑~原因很简单:你的文本所在的Column没有被设置宽度约束,导致Text可以无限延展,TextOverflow.ellipsis自然就起不到截断作用了。

问题根源

在Row组件中,如果子组件没有明确的宽度限制,像Text这种可以无限扩展的组件会一直撑满可用空间(甚至超出屏幕),这时候TextOverflow.ellipsis的截断逻辑根本不会触发——它不知道自己该在哪个宽度位置截断。

解决方案

给包裹歌曲标题和时长的Column外面套一层Expanded,让它占据左边Row里除了序号和间距之外的所有剩余宽度。这样Text就有了明确的最大宽度,溢出时就会自动显示省略号了。

修改后的代码

return Expanded(
 child: ListView.builder(
 itemCount: songss.length,
 itemBuilder: (context, index) {
 Song song = songss[index];
 return Container(
 decoration: BoxDecoration(
 border: Border(bottom: BorderSide(color: kPrimaryColor))),
 margin: const EdgeInsets.only(left: 16.0),
 child: InkWell(
 child: Column(
 children: <Widget>[
 SizedBox(height: 12.0),
 Row(
 mainAxisAlignment: MainAxisAlignment.spaceBetween,
 children: <Widget>[
 Row(
 children: <Widget>[
 Text("${index + 1}", style: Theme.of(context).textTheme.subtitle2),
 SizedBox(width: 16.0),
 // 这里添加Expanded包裹Column
 Expanded(
 child: Column(
 crossAxisAlignment: CrossAxisAlignment.start,
 children: <Widget>[
 Text(
 song.title,
 style: Theme.of(context).textTheme.subtitle1,
 overflow: TextOverflow.ellipsis,
 maxLines: 1, // 建议加上这个,确保只显示一行
 ),
 Text(_getSongDuration(song.duration), style: Theme.of(context).textTheme.subtitle2),
 ],
 ),
 ),
 ],
 ),
 Padding(
 padding: const EdgeInsets.only(right: 20.0),
 child: Row(
 children: <Widget>[
 IconButton(
 onPressed: () => null,
 icon: Icon(Icons.favorite_border),
 ),
 GestureDetector(
 onTapDown: (TapDownDetails details) => null,
 child: Icon(Icons.more_horiz),
 ),
 ],
 ),
 )
 ],
 ),
 SizedBox(height: 12.0),
 ],
 ),
 );
 },
 ),
 );

额外提示

  • 记得给Text加上maxLines: 1(如果只需要一行显示的话),这样截断效果会更明确;
  • 之前你用Expanded报错,大概率是因为把它加错了层级——Expanded必须是Row、Column或Flex的直接子组件,不能嵌套在其他组件里面;
  • 如果需要多行截断,可以把maxLines设为对应数字,比如2,配合TextOverflow.ellipsis就能实现多行末尾加省略号。

内容的提问来源于stack exchange,提问作者a_str0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:33:12