flutter中的ListView組件和GridView組件都是經常使用的佈局組件,有時候ListView中須要嵌套GridView來使用,例以下圖:javascript
這種狀況就須要在ListView裏面再嵌套一個GridView用於排放圖片等信息,先來看一下GridView一些經常使用的參數java
GridView.count( crossAxisCount: 3, // 每行顯示多少個 crossAxisSpacing: 1.5, // 橫軸網格間距 mainAxisSpacing: 1.5, // 縱軸網格間距 childAspectRatio: 11/16, // 網格比例 )
在GridView中的元素沒法設置其寬高,主要經過childAspectRatio來設置其比例,經過比例來顯示其大小。
在項目中若是直接使用ListView嵌套GridView進行佈局,其會出現報錯異常,例以下面異常:app
I/flutter ( 5969): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════ I/flutter ( 5969): The following assertion was thrown during performResize(): I/flutter ( 5969): Vertical viewport was given unbounded height. I/flutter ( 5969): Viewports expand in the scrolling direction to fill their container.In this case, a vertical I/flutter ( 5969): viewport was given an unlimited amount of vertical space in which to expand. This situation I/flutter ( 5969): typically happens when a scrollable widget is nested inside another scrollable widget. I/flutter ( 5969): If this widget is always nested in a scrollable widget there is no need to use a viewport because I/flutter ( 5969): there will always be enough vertical space for the children. In this case, consider using a Column I/flutter ( 5969): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size I/flutter ( 5969): the height of the viewport to the sum of the heights of its children.
出現這種狀況可在GridView中設置shrinkWrap:true便可解決:ide
GridView.count( shrinkWrap:true, // 處理listview嵌套報錯 ),
此時有可能出現手指在GridView區域滑動時ListView沒法進行滾動,處理該問題可在GridView中設置physics: NeverScrollableScrollPhysics()來處理:佈局
GridView.count( physics: NeverScrollableScrollPhysics(), // 處理GridView中滑動父級Listview沒法滑動 )