从firestorecollections快照中抓取数据.hasdata返回Null



所以我一直在遵循YouTube的教程,当我试图获取"用户名"从名为"users"的集合中通过流快照,它返回null。

目的:当用户名搜索按钮被点击时显示可用的用户

代码如下:

bool isSearching = false;
Stream? usersStream;
TextEditingController searchUsernameEditingController =
TextEditingController();
onSearchBtnClick() async {
isSearching = true;
setState(() {});
usersStream = await DatabaseMethods()
.getUserByUsername(searchUsernameEditingController.text);

setState(() {});
}
Widget searchUserList() {
return StreamBuilder(
stream: usersStream,
builder: (context, AsyncSnapshot snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.docs[index];
return Image.network(ds["imgUrl"]);
})
: Center(child: Text("No Users Found"));
});
}

从DatabaseMethods ():

Future<Stream<QuerySnapshot>> getUserByUsername(String username) async {
return FirebaseFirestore.instance
.collection("users")
.where("username", isEqualTo: username)
.snapshots();
}

总是显示"未找到用户";消息

首先确认当onSearchBtnClick被调用时streambuilder的新值被释放

试试这个。

onSearchBtnClick() async {
isSearching = true;
setState(() {});
}
Widget searchUserList() {
return StreamBuilder(
stream: DatabaseMethods()
.getUserByUsername(searchUsernameEditingController.text),
builder: (context, AsyncSnapshot snapshot) {
print('called');
// confirm that print is called when onSearchBtnClick is called.
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot ds = snapshot.data.docs[index];
return Image.network(ds["imgUrl"]);
})
: Center(child: Text("No Users Found"));
},
);
}

相关内容

  • 没有找到相关文章

最新更新