错误示范
Column(
children: <Widget>[
ListView(...),
],
)
当在编写 Flutter 应用时,直接在 Column 的 children 中包含了一个 ListView,则会出现如下报错:
======== Exception caught by rendering library =====================================================
The following assertion was thrown during paint():
RenderBox was not laid out: RenderRepaintBoundary#a63ed relayoutBoundary=up12 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1965 pos 12: 'hasSize'
Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.yml
原因与解决
https://stackoverflow.com/questions/45669202/how-to-add-a-listview-to-a-column-in-flutter
由于 Column 和 ListView 都向主坐标轴(垂直)扩张到最大值,所以会引起冲突。
所以,需要限制 ListView 的高度,一下提供几种方法,可以选择最适合自己的一种来解决:
1. Expand
如果 ListView 将会占用剩下的所有空间,直接用 Expand 将 ListView 包裹即可:
Column(
children: <Widget>[
Expanded( // <-- Use Expanded
child: ListView(...),
)
],
)
2. SizedBox
要手动限制 ListView 占用的高度,可以使用 Sizedox。
Column(
children: <Widget>[
SizedBox(
height: 200, // Constrain height.
child: ListView(...),
)
],
)
3. shrinkWrap
如果你的 ListView 很小,可以试试 shrinkWrap 属性:
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // Set this
)
],
)
4. Flexible + shrinkWrap
添加一个 Flexible 来让你的 ListView 尽可能小:
Column(
children: <Widget>[
Flexible( // <-- Use Flexible
child: ListView(
shrinkWrap: true, // and set this
),
)
],
)