问题

今天使用横向布局row 并且在里面添加了一个图标和一行文字,但是总是会超出布局,即使设置了overflow再调试时也会出现如下的情况

  1. Row(
  2. crossAxisAlignment: CrossAxisAlignment.center,
  3. children: <Widget>[
  4. Image.asset(
  5. "images/list_icon.png",
  6. width: 10,
  7. height: 10,
  8. fit: BoxFit.fill,
  9. ),
  10. Text(
  11. " "+hotService[index]['servicename'],
  12. maxLines: 1,
  13. style: TextStyle(
  14. fontSize: 14,
  15. decoration: TextDecoration.none),
  16. overflow: TextOverflow.ellipsis,
  17. )
  18. ],
  19. ),

flutter中text设置overflow还是会超出屏幕解决方法 - 图1
6D6EE3FE-B336-4475-ABD6-863075236C33.png

解决方法

直接在Text文字外面包一层Expanded(之前初学时,直接将Row改成Flex,因为Row继承自Flex,所以不用替换外层感谢周南城指出来)

  1. Row(
  2. crossAxisAlignment: CrossAxisAlignment.center,
  3. children: <Widget>[
  4. Image.asset(
  5. "images/list_icon.png",
  6. width: 10,
  7. height: 10,
  8. fit: BoxFit.fill,
  9. ),
  10. Expanded(child: Text(
  11. " "+hotService[index]['servicename'],
  12. maxLines: 1,
  13. style: TextStyle(
  14. fontSize: 14,
  15. decoration: TextDecoration.none),
  16. overflow: TextOverflow.ellipsis,
  17. ))
  18. ],
  19. ),

解决后如图所示

flutter中text设置overflow还是会超出屏幕解决方法 - 图2
6FF0A039-8FA4-4308-9B70-91B711B49A3E.png

出现问题的原因

因为刚开始学习,不是很了解,应该是横向row没有确定宽度,text根据内容来撑开row,所以就会超出,换成flex 使text最大宽度能占用剩下的所有宽度,所以达到最宽的时候就会显示省略号。
这个错误就好像再column中使用listView一样,会出现一个在无限高度的view中使用listView的错误,这个错误代码如下

  1. Column(
  2. children: <Widget>[
  3. ListView.builder(
  4. itemBuilder: (BuildContext con, int index) {
  5. return Text("index");
  6. },
  7. itemCount: 10,
  8. //下面的注释打开,可以解除报错
  9. //shrinkWrap: true,
  10. )
  11. ],
  12. ),
  13. //会出现的错误
  14. I/flutter (18787): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
  15. I/flutter (18787): The following assertion was thrown during performResize():
  16. I/flutter (18787): Vertical viewport was given unbounded height.
  17. I/flutter (18787): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
  18. I/flutter (18787): viewport was given an unlimited amount of vertical space in which to expand. This situation
  19. I/flutter (18787): typically happens when a scrollable widget is nested inside another scrollable widget.
  20. I/flutter (18787): If this widget is always nested in a scrollable widget there is no need to use a viewport because
  21. I/flutter (18787): there will always be enough vertical space for the children. In this case, consider using a Column
  22. I/flutter (18787): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
  23. I/flutter (18787): the height of the viewport to the sum of the heights of its children.
  • 解决column 嵌套listview的方法就是设置shrinkWrap,

shrinkWrap:该属性表示是否根据子widget的总长度来设置ListView的长度,默认值为false 。默认情况下,ListView的会在滚动方向尽可能多的占用空间。当ListView在一个无边界(滚动方向上)的容器中时,shrinkWrap必须为true

作者:eliteTyc
链接:https://www.jianshu.com/p/2851fe7b5183
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。