迁移到空安全后出现错误 未为类型“AsyncSnapshot
错误所在的代码片段
return FutureBuilder(
future: searchResultsFuture,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
List<UserResult> searchResults = [];
snapshot.docs.forEach((doc) { //have error here
User user = User.fromDocument(doc);
UserResult searchResult = UserResult(user);
searchResults.add(searchResult);
});
return ListView(
children: searchResults,
);
},
);
}
搜索结果未来
handleSearch(String query) {
Future<QuerySnapshot> users =
usersRef.where("displayName", isGreaterThanOrEqualTo: query).get();
setState(() {
searchResultsFuture = users;
});
}
clearSearch() {
searchController.clear();
}
答案 0 :(得分:1)
您代码中的 snapshot
是一个 AsyncSnapshot
,它确实没有 docs
子代。要从 Firestore 获取文档,您需要使用:
snapshot.data.docs
另请参阅 listening for realtime data 上的 FlutterFire 文档,其中包含显示此示例的示例 - 我的回答在这里解释了所有快照类型:What is the difference between existing types of snapshots in Firebase?
答案 1 :(得分:0)
通常,检索数据需要几毫秒的时间,所以我尝试这样做 确保在检索数据后执行我的操作
return StreamBuilder<QuerySnapshot>(
stream: Collectionreference
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> activitySnapshot) {
if (activitySnapshot.hasError) {
return Center(
child: Text('Something went wrong'),
);
}
if (activitySnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: SpinKitWave(
color: constants.AppMainColor,
itemCount: 5,
size: 40.0,
)));
}
if (!activitySnapshot.hasData || activitySnapshot.data.docs.isEmpty) {
return Center(
child: Text('Nothing to Display here'),
);
}
if (activitySnapshot.hasData) {
activitySnapshot.data.docs.forEach(doc=>{
print(doc);
})
}
}
});