android - 在flutter中设置childAspectRatio的正确方法
问题描述
在颤动中计算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]));
});
解决方案
免责声明:这是对 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
。
推荐阅读
- ios - 如何将文本字段值分配给 Xcode 上的变量?
- java - 我将此代码翻译成处理程序与原始代码有何不同?
- javascript - 如何在jquery中获取特定列名并为该列应用样式
- macos - 根据文件名 YYYY-MM 的开头将文件从一个文件夹移动到文件夹中的多个子文件夹
- python - How can I match the scale for 2 different variables in mark_circle() in Altair?
- f# - Seq.sumBy 与 Seq.groupBy
- azure-active-directory - Azure msal-angular 无法从 LocalStorage 读取身份验证属性?
- python - 在 Python 中循环遍历 XML
- python - 使用烧瓶和 html/react 打开 AI Gym cartpole 渲染
- javascript - 使用 URL 元素添加动态内容