本文介绍了输入“列表<动态>”不是类型“ List< Widget>”的子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Firestore示例中复制了一段代码:

I have a snippet of code which I copied from Firestore example:

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>'

这里出了什么问题?

推荐答案

这里的问题是类型推断失败一种意想不到的方式。解决方案是为 map 方法提供类型实参。

The problem here is that type inference fails in an unexpected way. The solution is to provide a type argument to the map method.

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

The更为复杂的答案是,虽然孩子的类型是 List< Widget> ,但这些信息不会流向 map 调用。这可能是因为 map 之后是 toList ,并且因为无法键入注释来返回闭包。

The more complicated answer is that while the type of children is List<Widget>, that information doesn't flow back towards the map invocation. This might be because map is followed by toList and because there is no way to type annotate the return of a closure.

这篇关于输入“列表&lt;动态&gt;”不是类型“ List&lt; Widget&gt;”的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:59