flutter - 是否可以使用 for 循环在 build 方法中创建小部件?
问题描述
我想制作一个不可滚动的网格,它的整体扩展到它的父级。我正在尝试在构建方法中运行一个 for 循环来创建行和列。但我收到以下错误
The element type 'Set<Row>' can't be assigned to the list type 'Widget'.
和
The element type 'Set<Text>' can't be assigned to the list type 'Widget'.
从 for 循环。为什么是这样?我该如何解决这个问题?
import 'package:flutter/material.dart';
class ExpandingGridArguments{
List<Widget> tiles;
int columns;
int rows;
ExpandingGridArguments(List<Widget> tiles, int columns)
{
this.tiles = tiles;
this.columns = columns;
this.rows = (tiles.length / columns).ceil();
}
}
class StaticGrid extends StatelessWidget {
@override
Widget build(BuildContext context) {
final ExpandingGridArguments arguments = ModalRoute.of(context).settings.arguments;
return Column(
children:
[
for(int c = 0; c < arguments.rows; c++ )
{
Row
(
children :
[
for(int r = 0; r < arguments.columns; r++)
{
Text('A row'),
}
]
),
}
]
);
}
}
解决方案
内部列表的语法与for
您所做的略有不同。
代替:
[
for (var i = 0; i < 42; i++) {
Text('$i')
}
]
它没有使用{}
:
[
for (var i = 0; i < 42; i++)
Text('$i')
]
这样做的原因{}
也用于创建Set
/ Map
:
Set<int> hashSet = {};
因此,{}
不支持使用内部列表来提高可读性,因为 Dart 会将“块”与创建Set
推荐阅读
- angular - 角度输入字段数据格式
- swift - 从 Xcode 应用程序执行终端命令时不允许操作
- html - 我需要了解 J 查询及其嵌套功能> 如何使用相同的目标将一个函数嵌套到另一个函数中?
- android - 构建 gradle 弃用
- powerquery - Power Query:为每个 FieldA 过滤行,给定 FieldB 中的最大值,速度非常慢
- database - 使用“AA”域/数据库的用户登录“BB”域/数据库
- python - 如何使用 Glove 和 CNN 配置和训练模型进行文本分类?
- python - 如何通过查找子数组的最小值和最大值对数组进行排序?
- gitlab - Gitlab覆盖解析有负百分比
- reactjs - 如何在 React 的 Azure B2C 流中获取没有过期刷新令牌