如何循环遍历列表以在 Flutter 和 Dart 中填充 Table?

How to loop through a list to populate a Table in Flutter and Dart?

我正在用 Flutter+Dart 编写一个移动应用程序,并且能够呈现用户的帐户信息,但我仍然不知道如何循环遍历列表以使用对象填充和呈现 table在该列表中,就在“用户帐户信息”下方。

这是我的 'Container',我不希望使用像 videos.removeAt(0) 这样的索引,并以某种方式遍历所有 videos 来填充 table.

Widget build(BuildContext context) {
    List<Video> videos = Video.getVideosFromJson(jsonDecode(json));
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Text('Account Info for ' + customer.firstName + ' ' + customer.lastName),
            Container(
              child: Padding(
                padding: const EdgeInsets.all(14.0),

     //TODO: HERE IS THE TABLE, I WISH TO DUPLICATE THESE ROWS FOR EACH "VIDEO" IN "List<Video> videos"

                child: Table(
                  border: TableBorder.all(width: 1.0, color: Colors.black),
                  children: [
                    TableRow(children: [
                      TableCell(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: <Widget>[
                            new Text('VideoId'),
                            new Text(videos.removeAt(0).id.toString()),
                          ],
                        ),
                      )
                    ]),

                    TableRow(children: [
                      TableCell(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: <Widget>[
                            new Text('Video Price'),
                            new Text(videos.removeAt(0).total.toString()),
                          ],
                        ),
                      )
                    ]),
                  ]
                )
              )
            )
          ]
      )
    );

解决这个问题的最佳方法是什么?

这是您可以执行的操作。

在 dart 2.3 以下你可以像这样使用地图:

Table(
  border: TableBorder.all(width: 1.0, color: Colors.black),
  children: videos.map((video){
    return TableRow(children: [
      TableCell(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            new Text('VideoId'),
            new Text(video.id.toString()),
          ],
        ),
      )
    ]);
  }).toList(),
);

对于 dart 2.3 及更高版本:

Table(
  border: TableBorder.all(width: 1.0, color: Colors.black),
  children: [
    for (var video in videos) TableRow(children: [
      TableCell(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            new Text('VideoId'),
            new Text(video.id.toString()),
          ],
        ),
      )
    ])
  ]
);

我想你正在寻找这样的东西:

List<TableRow> all = items.map<TableRow>((item) {
      return getTableRow(item);
    }).toList();

     Table(children: all);