参数类型 'List<CommentData>' 无法分配给参数类型 'List<Widget>

The argument type 'List<CommentData>' can't be assigned to the parameter type 'List<Widget>

我正在尝试使用从 firebase 查询的数据构建列表视图。但是报错'参数类型'List < CommentData >'不能赋值给参数类型'List< Widget >'代码如下

    Widget buildComments() {
    if (this.didFetchComments == false) {
      return FutureBuilder<List<CommentData>>(
          future: commentService.getComments(),
          builder: (context, snapshot) {
            if (!snapshot.hasData)
              return Container(
                  alignment: FractionalOffset.center,
                  child: CircularProgressIndicator());

            this.didFetchComments = true;
            this.fetchedComments = snapshot.data;
            return ListView(
              children: snapshot.data,  // where i'm having error
            );
          });
    } else {
      return ListView(children: this.fetchedComments); 
    }
  }

我该如何解决这个问题..

错误不言而喻

The argument type 'List<CommentData>' can't be assigned to the parameter type 'List<Widget>'

如果您想创建用于显示评论的列表 Text 小部件,您可以使用

return ListView.builder(
  itemCount: snapshot.data.length,
  itemBuilder: (context, index) => Text(snapshot.data[index].*), //What ever you want to show in from your model
);

snapshot.data returns List<CommentData> 而 ListView 的子项需要一个小部件列表,因此您会收到该错误。

尝试改变

return ListView(
   children: snapshot.data,
);

类似于:

return ListView(
   children: Text(snapshot.data[index].userName), //change userName to whatever field of CommentData class you want to show
);

我建议使用 ListView.Builder 来处理列表和索引。

ListView 期望 List<Widgets> 但你超过了 List<CommentData>

您可以将您的ListView修改为以下内容以纠正错误。

ListView.builder(
  itemCount: snapshot.data.length,
  itemBuilder: (context, index) {
    return Text(snapshot.data[index]['key']); //Any widget you want to use.
    },

);