flutter - 在 StreamBuilder 中渲染 ListView.ListTile
问题描述
我有一个 Flutter 应用程序,我试图在 StreamBuilder 中渲染一个 ListTile。
加载应用程序时出现此错误:
'Future<List>' 类型不是 'List' 类型的子类型
neabyComp() 函数片段:
Stream nearbyComp() async* {
var pos = await location.getLocation();
GeoFirePoint point =
geo.point(latitude: pos.latitude, longitude: pos.longitude);
final CollectionReference users =
_firebaseFirestore.collection("Companies");
double radius = 10;
String field = 'location';
Stream<List<DocumentSnapshot>> stream = geo
.collection(collectionRef: users)
.within(center: point, radius: radius, field: field, strictMode: true);
yield stream;
}
这是错误来自的 StreamBuilder 的代码片段:
Container(
child: StreamBuilder(
stream: nearbyComp(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return Container(
child: new ListView(
children: snapshot.data.map((document) {
// Adding snapshot.data.map<Widget> also returns error "Future<List<Widget>> is not a subtype of type List<Widget>"
return new ListTile(
title: new Text(document['companyName']),
subtitle: new Image.network(document['url']),
);
}).toList(),
),
);
},
),
),
解决方案
如果有人遇到这个问题,这里是@pskink 提供的解决方案(查找代码片段上的注释):
Stream nearbyComp() async* {
var pos = await location.getLocation();
GeoFirePoint point =
geo.point(latitude: pos.latitude, longitude: pos.longitude);
final CollectionReference users =
_firebaseFirestore.collection("Companies");
double radius = 10;
String field = 'location';
Stream<List<DocumentSnapshot>> stream = geo
.collection(collectionRef: users)
.within(center: point, radius: radius, field: field, strictMode: true);
yield* stream; // In this line, add the * after yield
}
另一部分在这里:
Container(
child: StreamBuilder(
stream: nearbyComp(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Loading");
}
return Container(
child: new ListView(
children: snapshot.data.map((document) {
// Add snapshot.data.map<Widget>
return new ListTile(
title: new Text(document['companyName']),
subtitle: new Image.network(document['url']),
);
}).toList(),
),
);
},
),
),
推荐阅读
- python-3.x - PyQT 改变内部 QVBoxLayout 在 GridLayout 中的位置
- python - 熊猫“加入”怪事
- knockout.js - Knockout.js 订阅可观察数组中的可观察元素
- c++ - 读取二进制格式的问题 [C++]
- c# - 匹配标记后第一个字符串的正则表达式
- c# - 来自数据库存储过程的 Gridview 数据源
- java - 如何从jsp中的jsp重定向到spring MVC控制器的另一个请求映射
- python - JSON 中缺少 Django (DRF) 布尔字段
- c++ - 无法转换 'std::vector
(*)[2]' 到 'std::vector **' 用于参数 '1' 到 'void getNextRowColumn(std::vector **)' - ios - 呈现视图控制器时键盘通知不一致