我试图避免在我需要访问当前用户 UID 的所有代码中使用 .then((u) { return u.uid })
函数,而只是通过调用getCurrentUser().uid
以获得更快的访问速度。但是,它给了我一个错误 The getter 'uid' was called on null.
但它不是 null,因为它确实在控制台中打印,但只有在显示它为 null 并且最后出现一些错误之后原因。我不太了解 Future/Async/Await 逻辑,因此非常感谢任何帮助!
class UsersAPI {
final DatabaseReference usersRef = FirebaseDatabase.instance.reference().child(Config.users);
Future<FirebaseUser> currentUser() async {
return await FirebaseAuth.instance.currentUser();
}
FirebaseUser getCurrentUser() {
FirebaseUser user;
this.currentUser().then((u) {
user = u;
print('USER 1 $user'); // Prints after 'USER 2'
});
print('USER 2 $user'); // Prints first
if (user != null) {
return user;
} else {
return null;
}
}
DatabaseReference getCurrentUserRef() {
return this.usersRef.child(this.getCurrentUser().uid); // GIVES THE 'uid' WAS CALLED ON NULL ERROR
}
observeCurrentUser(Function onSuccess(User u)) {
this.usersRef.child(this.getCurrentUser().uid).onValue.listen( (event) { // GIVES THE 'uid' WAS CALLED ON NULL ERROR
DataSnapshot snapshot = event.snapshot;
if (snapshot.value != null) {
User user = User().transform(snapshot.key, snapshot.value);
onSuccess(user);
}
});
}
observeUser(String userID, Function onSuccess(User u), Function onFailure(String e)) {
this.usersRef.child(userID).onValue.listen( (e) {
DataSnapshot snapshot = e.snapshot;
if (snapshot.value != null) {
User user = User().transform(snapshot.key, snapshot.value);
onSuccess(user);
} else {
onFailure("User Not Found...");
}
});
}
}
示例用法 - WORKS:
APIs().usersAPI.currentUser().then((u) {
APIs().usersAPI.observeUser(u.uid, (u) {
onSuccess(u);
}, (e) {
print(e);
});
});
不起作用:
APIs().usersAPI.observeCurrentUser((u) {
onSuccess(u);
});
最佳答案
DatabaseReference getCurrentUserRef() async {
return this.usersRef.child((await this.getCurrentUser()).uid); =
}
比调用
var ref = await getCurrentUserRef()
漂亮一点
DatabaseReference getCurrentUserRef() async {
var firebaseUser = await this.getCurrentUser();
return this.usersRef.child(firebaseUser.uid);
}
编辑:澄清一些关于异步的问题
您现在如何调用此函数来获取引用?
假设你想更新用户的数据,你可以这样做
Firestore.instance.runTransaction((transaction) async {
var reference = await getCurrentUserRef();
await transaction.set(reference, someData);
});
或者你想从那个引用中读取数据
readAndProcessData() async {
var reference = await getCurrentUserRef();
DocumentSnapshot user = await reference.get();
print(user.data.toString);
}
关于firebase - flutter/火力基地 : How can i access the current user without using '.then(...)' function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50727697/