在Column内部使用ListView会导致“Vertical viewport was given unbounded height”错误。

11

我是Flutter的新手,对于布局方面遇到了一些困难。

我想要实现类似于这样的效果: a sticky header and a scroll view below

一个粘性的标题和它下面的可滚动视图。 我考虑使用Column widget,并将其分为两个子项-第一个是标题,第二个是ListView。

以下是我的代码:

 Widget build(BuildContext context) {
 return Material(
   elevation: 8.0,
   child: Column(
     crossAxisAlignment: CrossAxisAlignment.start,
     children: <Widget>[
       Padding(
         padding: const EdgeInsets.all(16.0),
         child: Text(
           title,
           style:
               Theme.of(context).textTheme.subhead.copyWith(fontSize: 18.0),
           textAlign: TextAlign.left,
         ),
       ),
       Divider(height: 4.0),
       ListView.builder(itemBuilder: (context, i) {
         return ListTile(
           title: Text("Title $i"),
           subtitle: Text("Subtitle $i"),
         );
       }),
     ],
   ),
 );
}

我对此遇到了以下错误。

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

我按照消息中提到的添加了ListView的shrinkWrap属性,但那也没有起作用。

此布局的父级是一个堆栈,其中包含各种这样的布局页面,所有这些布局页面都处于关闭状态,用户选择的页面除外。

我做错了什么?


另请参阅 https://medium.com/cwi-software/flutter-tips-and-tricks-1f0c0189185b#b23a - User
2
我认为这个问题的标题可以改进一下。也许可以改成像“在Column中使用ListView导致'垂直视口高度未被限定'”或者“ListView出现'垂直视口高度未被限定'错误”的标题。 - User
1个回答

25

尝试使用FlexibleExpanded小部件包装您的ListView.builder

Flexible(
            child: ListView.builder(
              itemBuilder: (context, i) {
                return ListTile(
                  title: Text("Title $i"),
                  subtitle: Text("Subtitle $i"),
                );
              },
            ),
          ),

2
这对我有用,谢谢。我不知道为什么在Flutter的如何构建布局文档中没有提到Flexible。我尝试了ConstrainedBox、FittedBox、Expand等所有东西...无论如何还是感谢您的帮助。 - Harsh Bhikadia
1
这与您的ListView具有无限数量的子项有关,它需要告知如何适应其所给定的无限大小。 - Shady Aziza
4
无法运行,现在出现了“RenderFlex的子级具有非零flex,但传入的高度约束未被限制”的错误提示。 - giorgio79

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接