首页 > 解决方案 > 在flutter中设置childAspectRatio的正确方法

问题描述

在颤动中计算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]));
    });

标签: androidiosflutterflutter-layoutflutter-sliver

解决方案


免责声明:这是对 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 / 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


推荐阅读