【问题标题】:The argument type 'List<CommentData>' can't be assigned to the parameter type 'List<Widget>参数类型“List<CommentData>”不能分配给参数类型“List<Widget>”
【发布时间】:2021-07-04 23:36:45
【问题描述】:

我正在尝试使用从 firebase 查询的数据构建列表视图。但是我有一个错误'参数类型'List '不能分配给参数类型'List'代码如下

    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); 
    }
  }

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

【问题讨论】:

    标签: firebase flutter flutter-listview


    【解决方案1】:

    ListView 需要 List&lt;Widgets&gt;,但您正在传递 List&lt;CommentData&gt;

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

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

    【讨论】:

      【解决方案2】:

      错误会自己说话

      参数类型“List&lt;CommentData&gt;”不能分配给参数类型“List&lt;Widget&gt;

      如果你想创建 List 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
      );
      

      【讨论】:

        【解决方案3】:

        snapshot.data 返回 List&lt;CommentData&gt; 而 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 来处理列表和索引。

        【讨论】:

          猜你喜欢
          • 2021-10-24
          • 2021-09-13
          • 1970-01-01
          • 2021-12-10
          • 2022-11-05
          • 2021-06-04
          • 2021-11-05
          • 2020-08-26
          • 1970-01-01
          相关资源
          最近更新 更多