Flutter中用ListView嵌套GridView報錯異常


flutter中的ListView組件和GridView組件都是常用的布局組件,有時候ListView中需要嵌套GridView來使用,例如下圖:

這種情況就需要在ListView里面再嵌套一個GridView用於排放圖片等信息,先來看一下GridView一些常用的參數

GridView.count(
  crossAxisCount: 3,                            // 每行顯示多少個
  crossAxisSpacing: 1.5,                        // 橫軸網格間距
  mainAxisSpacing: 1.5,                         // 縱軸網格間距
  childAspectRatio: 11/16,                      // 網格比例
)

在GridView中的元素無法設置其寬高,主要通過childAspectRatio來設置其比例,通過比例來顯示其大小。

在項目中如果直接使用ListView嵌套GridView進行布局,其會出現報錯異常,例如下面異常:

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即可解決:

GridView.count(
  shrinkWrap:true,                              // 處理listview嵌套報錯
),

  

此時有可能出現手指在GridView區域滑動時ListView無法進行滾動,處理該問題可在GridView中設置physics: NeverScrollableScrollPhysics()來處理:

GridView.count(
  physics: NeverScrollableScrollPhysics(),      // 處理GridView中滑動父級Listview無法滑動
)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM