水平 SingleChildScrollView 内的垂直 ListView

Dav*_*ego 7 flutter flutter-layout

我需要构建一个页面,其中包含分组在一行中的对象列表。需要垂直滚动(以显示更多组)和水平滚动(以显示组子项)。\n垂直和水平滚动需要完全移动项目。\n类似这样的内容:https ://gph.is/g/ 46gjW0q

\n\n

我正在使用以下代码执行此操作:

\n\n
Widget _buildGroups() {\n    return SingleChildScrollView(\n      scrollDirection: Axis.horizontal,\n      child: Container(\n        width: 2000,\n        child: ListView.builder(\n          scrollDirection: Axis.vertical,\n          itemCount: boardData.length,\n          itemBuilder: (context, index) {\n            return Row(children: _buildSingleGroup(index));\n          },\n        ),\n      ),\n    );\n}\n\nList<Widget> _buildSingleGroup(int groupIndex) {\n    return List.generate(...);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我需要它是水平动态的,但在这里,正如你所看到的,我需要设置一个宽度,否则会发生错误:

\n\n
\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90 Exception caught by rendering library \xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\nThe following assertion was thrown during performResize()\nVertical viewport was given unbounded width.\n\nViewports expand in the cross axis to fill their container and constrain their \nchildren to match their extent in the cross axis. In this case, a vertical \nviewport was given an unlimited amount of horizontal space in which to expand.\n
Run Code Online (Sandbox Code Playgroud)\n\n

我尝试在 ListView 中设置“shrinkWrap: true”,但结果给出了另一个错误:

\n\n
Failed assertion: line 1629 pos 16: \'constraints.hasBoundedWidth\': is not true.\n
Run Code Online (Sandbox Code Playgroud)\n\n

那么如何使用动态 ListView 宽度来做到这一点呢?

\n

Mis*_*rov 2

发生错误的原因是,当ListView尝试从其父级获取高度以填充整个高度时,父级返回无穷大高度,因为SingleChildScrollView没有固定的容器高度值。要解决该问题,您需要限制高度值。例如,我曾经SizedBox指定 的高度ListView

以下代码对我有用。

SingleChildScrollView(
  child: Column(
    mainAxisSize: MainAxisSize.min,
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      SizedBox(
        height: 120, // <-- you should put some value here
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: items.length,
          itemBuilder: (context, index) {
            return Text('it works');
          },
        ),
      ),
    ],
  ),
);
Run Code Online (Sandbox Code Playgroud)