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

P_e*_*021 1 mobile dart dart-pub flutter

我正在 Flutter+Dart 中编写一个移动应用程序,并且能够渲染用户的帐户信息,但我一直坚持如何循环遍历列表以填充和渲染带有该列表中的对象的表,就在用户帐户下方信息。

这是我的“容器”,我希望不使用类似的索引videos.removeAt(0)并以某种方式循环遍历所有索引来videos填充表。

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()),
                          ],
                        ),
                      )
                    ]),
                  ]
                )
              )
            )
          ]
      )
    );
Run Code Online (Sandbox Code Playgroud)

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

Adn*_*rim 5

这是您可以做的。

在 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(),
);
Run Code Online (Sandbox Code Playgroud)

对于 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()),
          ],
        ),
      )
    ])
  ]
);
Run Code Online (Sandbox Code Playgroud)