在flutter中设置childAspectRatio的正确方法

时间:2019-05-10 06:05:10

标签: android ios flutter flutter-layout flutter-sliver

在抖动中计算 SliverGridDelegateWithFixedCrossAxisCount childAspectRatio 的正确方法是什么?如何管理与所有设备兼容并且可以横向和纵向使用的每个视图的正确高度

GridView.builder(
    physics: BouncingScrollPhysics(),
    padding: const EdgeInsets.all(4.0),
    itemCount: snapshot.data.results.length,
    gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: itemCount,
      childAspectRatio: 0.501,
      mainAxisSpacing: 4.0,
      crossAxisSpacing: 4.0,
    ),
    itemBuilder: (BuildContext context, int index) {
      return GridTile(
          child: _buildGridItem(context, snapshot.data.results[index]));
    });

1 个答案:

答案 0 :(得分:0)

免责声明:这是GridView的工作原理的理论解释。建议的解决方案不是为大量内容而设计的。使用我在这里描述的GridView理论构建所需的布局。

让我从crossAxisCount开始,它应该被解释为表中的许多列。

例如crossAxisCount: 3,

|  cell-1  ||  cell-2  ||  cell-3  |
------------------------------------ // new row after every 3 cells
|  cell-4  ||  cell-5  ||  cell-6  |

颤动对crossAxisCount: N,的作用是试图完全适合一行中N个单元格的数量。因此,一个单独单元格的宽度等于栅格宽度除以N

例如crossAxisCount: 3,-> cellWidth = parentWidth / 3 (伪代码)


现在,接下来发生的是使用您最初提出问题的childAspectRatio计算像元的高度。

例如cellWidth = parentWidth / crossAxisCountcellHeight = cellWidth / childAspectRatio

这样,您应该将childAspectRatio解释为每个单个单元格的宽度与高度之比(反之亦然)。


我认为您注意到GridView在结构异常的布局方面相当有限。

如果您真的认为GridView不足以满足您要构建的内容-我建议您使用支持多个子布局的其他小部件。例如,我使用Wrap小部件来显示非常流畅的内容,其中每个元素都有自己的动态宽度和高度。

我不知道您需要哪种布局,但是在动态/流畅但轻巧的概念下,您可以尝试使用Wrap

@override
Widget build(BuildContext context) {
  final mediaQuery = MediaQuery.of(context);
  return SingleChildScrollView(
    child: Wrap(
      children: List.generate(totalItemsToDisplay, (index) {
        final cellWidth = mediaQuery.size.width / 3; // Every cell's `width` will be set to 1/3 of the screen width.
        return SizedBox(
          width: cellWidth,
          // You can either use some static number for `height`, or set ratio to cellWidth.
          // Setting `height` to `null` should work too, which would make height of a cell auto-resizable according to its content.
          height: 123,
          child: ...,
        );
      })
    )
  );
}

但是,我不建议您使用它来显示大量数据。

如果您的目标是显示一组帖子/文章/图片等,这最初意味着结构化的大量内容-我建议通过将childAspectRatio的单元格高度标准化来使用GridView。 / p>