gpt4 book ai didi

firebase - Flutter:Firestore在StreamBuilder中获取用户uid

转载 作者:行者123 更新时间:2023-12-03 03:33:11 25 4
gpt4 key购买 nike

我有一个应用程序,我想在集合中显示文档。集合引用是用户的uid。
有没有一种方法可以获取当前用户uid并将此uid放入StreamBuilder中。
我已经尝试过了,但是没有成功,返回null:

class _MyAdsState extends State<MyAds> {

final FirebaseAuth _auth = FirebaseAuth.instance;

Future getCurrentUser() async {
final FirebaseUser user = await _auth.currentUser();
final uid = user.uid;
print(uid);
return uid.toString();
}

@override
Widget build(BuildContext context) {
return Scaffold(

body: Column(
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection("${getCurrentUser()}").snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> querySnapShot){
if(querySnapShot.hasError){
return Text('Some Error');
}
if(querySnapShot.connectionState == ConnectionState.waiting){
return CircularProgressIndicator();
}else{
final list = querySnapShot.data.documents;

return ListView.builder(
itemBuilder: (context, index){
return ListTile(
title: Text(list[index]["subject"]),
subtitle: Text(list[index]["category"]),
);
},
itemCount: list.length,
);
}
},
)

最佳答案

获取UID是异步操作,因此需要FutureBuilder
如果要使用UID来构建流,则需要为UID提供FutureBuilder,然后在其中为数据库中的流提供StreamBuilder

body: FutureBuilder(
future: FirebaseAuth.instance.currentUser(),
builder: (context, AsyncSnapshot<FirebaseUser> snapshot) {
if (snapshot.hasData) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection(snapshot.data.uid).snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> querySnapShot){
...
},
)
}
else {
return Text('Loading user data...');
}

关于firebase - Flutter:Firestore在StreamBuilder中获取用户uid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62603101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com