我有一个 2x2 网格,我试图用卡片填充它,其中每张卡片都有特定的样式。每张卡片都有一个标题和一条路线,单击它会打开另一页(路线)。我想为“名称”索引中的每个“名称”指定卡片的“名称”和点击应指向的“页面名称”。
问题是 1。我不确定如何在小部件中执行 for-each 循环。 2. 不确定如何使这项工作适用于超过 1 个参数;卡片名称和新页面名称。
我已经尝试了几个选项,其中 2 个如下所示。
class SubjectsPage extends StatefulWidget {
@override
_SubjectsPageState createState() => new _SubjectsPageState();
}
class _SubjectsPageState extends State<SubjectsPage> with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
var names = ["one", "two", "three", "four"];
return new Material(
child: new Container(
child: new Center(
child: GridView.count(
crossAxisCount: 2,
padding: EdgeInsets.fromLTRB(16.0, 128.0, 16.0, 16.0),
childAspectRatio: 8.0 / 8.5,
children: <Widget>[
//option 1
names.forEach((unit) => Cards(unit: unit,)),
//option 2
for (var i = 0; i < names.length; i++) {
Cards(unit: names[i])
}
],
),
),
),
);
}
}
选项 1 的错误是“此处的表达式具有 'void' 类型,因此不能使用。”
选项 2 的错误是“无法将元素类型‘Set’分配给列表类型‘Widget’。”
最佳答案
是的,您不能使用 forEach
,但可以使用 map
。您可以使用 map
方法将字符串映射到小部件。
例子:
class SubjectsPage extends StatefulWidget {
@override
_SubjectsPageState createState() => new _SubjectsPageState();
}
class _SubjectsPageState extends State<SubjectsPage>
with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
var names = ["one", "two", "three", "four"];
return Material(
child: Container(
child: Center(
child: GridView.count(
crossAxisCount: 2,
padding: EdgeInsets.fromLTRB(16.0, 128.0, 16.0, 16.0),
childAspectRatio: 8.0 / 8.5,
children: names.map((String name) {
return Cards(unit: name);
}).toList(),
),
),
),
);
}
}
或者:您的选项二可以像这样完成
class SubjectsPage extends StatefulWidget {
@override
_SubjectsPageState createState() => new _SubjectsPageState();
}
class _SubjectsPageState extends State<SubjectsPage>
with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
var names = ["one", "two", "three", "four"];
return Material(
child: Container(
child: Center(
child: GridView.count(
crossAxisCount: 2,
padding: EdgeInsets.fromLTRB(16.0, 128.0, 16.0, 16.0),
childAspectRatio: 8.0 / 8.5,
children: [
for(String name in names) Cards(unit:name)
],
),
),
),
);
}
}
希望对您有所帮助!
关于loops - 列表中每个项目的 Flutter 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56986590/