小编典典

输入“列表'不是'List类型的子类型'

flutter

我有一个从Firestore示例复制的代码片段:

Widget _buildBody(BuildContext context) {
    return new StreamBuilder(
      stream: _getEventStream(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return new Text('Loading...');
        return new ListView(
          children: snapshot.data.documents.map((document) {
            return new ListTile(
              title: new Text(document['name']),
              subtitle: new Text("Class"),
            );
          }).toList(),
        );
      },
    );
  }

但是我得到这个错误

type 'List<dynamic>' is not a subtype of type 'List<Widget>'

这里出什么问题了?


阅读 240

收藏
2020-08-13

共1个答案

小编典典

这里的问题是类型推断以意外的方式失败。解决方案是为该map方法提供类型实参。

snapshot.data.documents.map<Widget>((document) {
  return new ListTile(
    title: new Text(document['name']),
    subtitle: new Text("Class"),
  );
}).toList()

更为复杂的答案是,尽管类型childrenList<Widget>,但信息不会流回map调用。这可能是因为map紧随其后的toList原因,并且是因为无法键入注释来返回闭包。

2020-08-13