問題
今天使用橫向布局row 并且在里面添加了一個圖標和一行文字,但是總是會超出布局,即使設置了overflow再調試時也會出現如下的情況
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Image.asset(
"images/list_icon.png",
width: 10,
height: 10,
fit: BoxFit.fill,
),
Text(
" "+hotService[index]['servicename'],
maxLines: 1,
style: TextStyle(
fontSize: 14,
decoration: TextDecoration.none),
overflow: TextOverflow.ellipsis,
)
],
),
6D6EE3FE-B336-4475-ABD6-863075236C33.png
解決方法
直接在Text文字外面包一層Expanded(之前初學時,直接將Row改成Flex,因為Row繼承自Flex,所以不用替換外層感謝周南城指出來)
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Image.asset(
"images/list_icon.png",
width: 10,
height: 10,
fit: BoxFit.fill,
),
Expanded(child: Text(
" "+hotService[index]['servicename'],
maxLines: 1,
style: TextStyle(
fontSize: 14,
decoration: TextDecoration.none),
overflow: TextOverflow.ellipsis,
))
],
),
解決后如圖所示
6FF0A039-8FA4-4308-9B70-91B711B49A3E.png
出現問題的原因
因為剛開始學習,不是很了解,應該是橫向row沒有確定寬度,text根據內容來撐開row,所以就會超出,換成flex 使text最大寬度能占用剩下的所有寬度,所以達到最寬的時候就會顯示省略號。
這個錯誤就好像再column中使用listView一樣,會出現一個在無限高度的view中使用listView的錯誤,這個錯誤代碼如下
Column(
children: <Widget>[
ListView.builder(
itemBuilder: (BuildContext con, int index) {
return Text("index");
},
itemCount: 10,
//下面的注釋打開,可以解除報錯
//shrinkWrap: true,
)
],
),
//會出現的錯誤
I/flutter (18787): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter (18787): The following assertion was thrown during performResize():
I/flutter (18787): Vertical viewport was given unbounded height.
I/flutter (18787): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter (18787): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter (18787): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter (18787): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter (18787): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter (18787): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
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