首页 > 解决方案 > 参数类型'列表?不能分配给参数类型“列表”'

问题描述

我想为我的应用程序创建一个聊天。我需要使用flutter在firebase中显示我在我的用户集合中拥有的所有用户的名称字段。下图类似于我正在尝试做的事情。

[ 1]

这是我的代码:

          stream: FirebaseFirestore.instance.collection('users').snapshots(),
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (!snapshot.hasData) {
              return Text("You have no contact.");
            }
            return ListView (
              children: snapshot.data?.docs.map(
                (doc){ 
                  new Text(doc["fullName"]);
                  }
              ).toList(), // all the children is making an error
            );
          }
        )

这是我遇到的问题:The argument type 'List<Null>?' can't be assigned to the parameter type 'List<Widget>'.

我猜这个问题来自我的快照,它没有包含在一个小部件中,但是我从中获得灵感的代码做了同样的事情并且似乎没有任何问题。他们的代码:return ListView( children: snapshot.data.documents.map((document){}).toList(),

有人知道吗?谢谢你读我

标签: flutter

解决方案


您已经用块体声明了您的函数,但您没有使用 return 命令来返回小部件!

通过返回 Text 小部件来修复它:

            return ListView (
              children: snapshot.data?.docs.map(
                (doc){ 
                  return new Text(doc["fullName"]);
                  }
              ).toList(), // all the children is making an error
            );

您还可以用箭头函数替换块体:

            return ListView (
              children: snapshot.data?.docs.map(
                (doc) => 
                   new Text(doc["fullName"])
              ).toList(), // all the children is making an error
            );

FIX:如果您遇到错误

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

然后将列表转换为List<Widget>

snapshot.data?.docs.map(
                (doc) => 
                   new Text(doc["fullName"])
              ).toList() as List<Widget>

推荐阅读