在Flutter中设置childAspectRatio的正确方法

10

在Flutter中,计算SliverGridDelegateWithFixedCrossAxisCountchildAspectRatio的正确方法是什么?如何管理每个视图的正确高度,以便与所有设备兼容并且在横向和纵向上都能正常工作。

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
这个问题比较宽泛。你能让问题更具体一些吗? - Rémi Rousselet
有没有一个公式可以计算childAspectRatio? - Ashwin S Ashok
你能举个例子,说明需要计算宽高比的孩子吗? - Saed Nabil
只需考虑 https://45eqks401uca3p9xje465puo-wpengine.netdna-ssl.com/wp-content/uploads/sites/4/2013/09/mceclip10-1.png 中的项目网格视图。如何在不同设备上进行管理。 - Ashwin S Ashok
1个回答

5

声明:这是GridView如何工作的理论解释。所提出的解决方案不适用于大量内容。请按照我在这里描述的GridView理论构建所需的布局。

让我们从crossAxisCount开始,它应该被解释为表格中的列数。

例如:crossAxisCount: 3

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

Flutter通过使用 crossAxisCount: N, 来尝试在一行中恰好容纳N个单元格。因此,一个单独的单元格的宽度将等于网格的宽度除以N
例如:crossAxisCount: 3, -> cellWidth = parentWidth / 3(伪代码) 接下来,计算单元格的高度使用你初始问题中提到的childAspectRatio
例如:cellWidth = parentWidth / crossAxisCount & cellHeight = 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: ...,
        );
      })
    )
  );
}

然而,我不建议使用它来显示大量数据集。
如果您的目标是展示一组文章、图片等内容,这些内容本质上含有结构性的繁重内容 - 我建议使用GridView,通过childAspectRatio标准化单元格高度。

如何通过childAspectRatio标准化单元格高度? - Ashwin S Ashok
@AshwinSAshok 我的意思是所有单元格都将根据 childAspectRatio 具有相同的大小。如果您有动态大小的元素 - 您可能希望使用我提出的 Wrap 解决方案。 - George Zvonov
你已经提到过:“Wrap:我不建议使用它来显示大量数据。” 那么有没有可能计算出childAspectRatio呢? - Ashwin S Ashok

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