flutter 如何在小部件的子部件中使用“for”循环?

igsr9ssn  于 2023-01-31  发布在  Flutter
关注(0)|答案(5)|浏览(248)

我真的很困惑,FOR循环应该放在哪里,这样我就不会在flutter中出错了,正如你在图片中看到的,它有红色的下划线,它说。

ulydmbyx

ulydmbyx1#

两个备选方案:

final children = <Widget>[];
for (var i = 0; i < 10; i++) {
  children.add(new ListTile());
}
return new ListView(
  children: children,
);

return new ListView(
  children: new List.generate(10, (index) => new ListTile()),
);
5ssjco0h

5ssjco0h2#

ListViewColumn等小部件的子级中使用for循环有多种方式。

  • 使用for循环
ListView(
  children: [
    for (var i = 0; i < 10; i++) Text('Item $i'),
  ],
)
  • 使用for-each循环
ListView(
  children: [
    for (var item in items) Text(item),
  ],
)
  • ...[]for循环结合使用
ListView(
  children: [
    ...[
      Text('Item 0'),
      Text('Item 1'),
    ],
    for (var item in items) Text(item), // Rest of the items
  ],
)
j5fpnvbx

j5fpnvbx3#

我们还可以使用spread操作符,通过for循环添加多个小部件

Column(
 children: [
 Container() /// we can add some other widgets
 for (var i = 0; i < 3; i++) ...[
    CardListItem(),
    Divider(),
  ],
]
qyuhtwio

qyuhtwio4#

使用json响应的Flutter中的简单for循环

Widget build(BuildContext context) {
var list = [{'id':"123123","date":"20/08/2016"},{'id':"123124","date":"26/08/2016"},{'id':"123125","date":"26/08/2016"}]; 
   return Scaffold(
  appBar: AppBar(
    title: Text(widget.title),
  ),
  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text('Recent Claims'),
        Table(
          border: TableBorder.all(color: Colors.black),
          columnWidths: {
            0: FixedColumnWidth(100.0),
            1: FixedColumnWidth(100.0)
          },
          children:[
            for(var item in list )  TableRow(children: [
              Text(item['id']),
              Text(item['date']),
          ])]
           ),
      }
qoefvg9y

qoefvg9y5#

如果您没有List

ListView(
  scrollDirection: Axis.horizontal,
  children: List.generate(10, (index) => …),
),

其他:

ListView(
  scrollDirection: Axis.horizontal,
  children: list.map((e) => …).toList(),
),

相关问题