Flutter 避坑之 GridView/ListView 显示问题

4,103 阅读2分钟

问题引出

学习Flutter中,将现在的原生app用Flutter开发,开发到主页的时候遇到了一个问题:

在使用GridViewView的时候不能显示很是郁闷,我是在Column里面使用的GridView,先上代码:

@override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          height: MediaQuery.of(context).padding.top,
          color: ColorDef.colorPrimary,
        ),
        Weather(),
        Container(
          padding: EdgeInsets.fromLTRB(
              Dimens.marginWindow, 0, Dimens.marginWindow, 0),
          child: GridView.count( 
            crossAxisCount: 3,
            mainAxisSpacing: 15,
            // Generate 100 widgets that display their index in the List.
            children: List.generate(userResList.length, (index) {
              return getChild(index);
            }),
          ),
        ),
      ],
    );
  }

运行时,控制台输出如下

I/flutter ( 8000): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 8000): The following assertion was thrown during performResize():
I/flutter ( 8000): Vertical viewport was given unbounded height.
I/flutter ( 8000): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 8000): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 8000): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter ( 8000): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter ( 8000): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter ( 8000): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter ( 8000): the height of the viewport to the sum of the heights of its children.

根据第二行可以看出是高度的问题,接着看,一个无限垂直扩充的视图,即我们的GridView(也是 scrollable widget)需要被另一个可滑动的视图包裹(a scrollable widget is nested inside another scrollable widget.); ('there will always be enough vertical space for the children.')这句话可以了解到,Column不能提供足够的垂直空间给GridView,也就是无法为GridView计算空间

否则,'using the "shrinkWrap" property'

解决1

一看使用'shrinkWrap'属性简单点,于是我就给GridView加上了 'shrinkWrap: true,'这句话

效果如下(上半部分,没有截下来),如果GridView内容没有超过可见范围,就不会有下面提示('BOTTOM OVERFLOWED BY 142 PIXELS'), 所以你能确保不出问题就可以这样用,否则看解决2

解决2

'a scrollable widget is nested inside another scrollable widget.'

使用可滑动Widget(scrollable widget)包裹我们的GridView就好了,代码如下:

Expanded(
          child: Container(
            padding: EdgeInsets.fromLTRB(
                Dimens.marginWindow, 0, Dimens.marginWindow, 0),
            child: GridView.count(
              crossAxisCount: 3,
              childAspectRatio: 5 / 4,
              children: List.generate(userResList.length, (index) {
                return getChild(index);
              }),
            ),
          ),
        ),