输入“列表'不是'List类型的子类型'
问题内容:
我有一个从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>'
这里出什么问题了?
问题答案:
这里的问题是类型推断以意外的方式失败。解决方案是为该map
方法提供类型实参。
snapshot.data.documents.map<Widget>((document) {
return new ListTile(
title: new Text(document['name']),
subtitle: new Text("Class"),
);
}).toList()
更为复杂的答案是,尽管类型children
为List<Widget>
,但信息不会流回map
调用。这可能是因为map
紧随其后的toList
原因,并且是因为无法键入注释来返回闭包。