跳到主要内容

Flutter中用ListView嵌套GridView报错异常

管

管理员

https://www.cnblogs.com/gxsyj/p/11024334.html

2020年10月20日 3,440 次阅读
本页目录

listView嵌套GridView可能会出现如下错误:

Vertical viewport was given unbounded height.

分析原因可能是因为 尝试通过子组件的实际尺寸来调整自身尺寸,这就导致他们的子组件不能是延迟加载模型的组件(如ListView、GridView 、 CustomScrollView等),解决办法就是把内部无限高度设置自动收缩,或者增加一个高度.

转载:
flutter中的ListView组件和GridView组件都是常用的布局组件,有时候ListView中需要嵌套GridView来使用,例如下图:

这种情况就需要在ListView里面再嵌套一个GridView用于排放图片等信息,先来看一下GridView一些常用的参数

1
2
3
4
5
6
GridView.count(
  crossAxisCount: 3,                            // 每行显示多少个
  crossAxisSpacing: 1.5,                        // 横轴网格间距
  mainAxisSpacing: 1.5,                         // 纵轴网格间距
  childAspectRatio: 11/16,                      // 网格比例
)

在GridView中的元素无法设置其宽高,主要通过childAspectRatio来设置其比例,通过比例来显示其大小。

在项目中如果直接使用ListView嵌套GridView进行布局,其会出现报错异常,例如下面异常:

1
2
3
4
5
6
7
8
9
10
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即可解决:

1
2
3
GridView.count(
  shrinkWrap:true,                              // 处理listview嵌套报错
),

  

此时有可能出现手指在GridView区域滑动时ListView无法进行滚动,处理该问题可在GridView中设置physics: NeverScrollableScrollPhysics()来处理:

1
2
3
GridView.count(
  physics: NeverScrollableScrollPhysics(),      // 处理GridView中滑动父级Listview无法滑动
  primary:false //或者

)

  

Related

相关文章

同分类文章 →
2026年07月28日 flutter

Dart 3 记录(Records)和密封类(Sealed classes)

Dart 3 引入了几个极其强大的语言特性,其中最耀眼、对我们日常开发改变最大的就是 记录(Records) 和 密封类(Sealed classes),它们配合 模式匹配(Pattern Matching),让 Dart 的表现力达到了现代编程语言(如 Swift、Kotlin、Rust

2026年06月29日 flutter

flutter的 Clean Architecture架构设计

Clean Architecture(清晰架构)是一种将应用程序分层的设计模式,强调关注点分离与依赖规则,通过将业务逻辑与框架、UI、数据源解耦,提升代码的可测试性、可维护性与可扩展性。在 Flutter/Dart 环境下,Clean Architecture 通

2025年12月22日 flutter

Riverpod 实战:如何优雅地实现网络请求的防抖与取消

在开发复杂的应用程序时,管理网络请求的生命周期至关重要。例如,用户在搜索框快速输入时可能会触发大量请求,或者在请求完成前离开页面,导致不必要的资源浪费。本文将介绍如何在 Riverpod 中利用 ref.onDispose 和“

WeChat

扫码加我微信

微信二维码