gpt4 book ai didi

firebase - 如何返回 firebase 用户以访问某些元素

转载 作者:IT王子 更新时间:2023-10-29 07:21:06 26 4
gpt4 key购买 nike

我正在尝试在一个文件中编写一个函数以获取其他文件中的当前登录用户。

现在,我只是让它返回用户,但是,当调用该函数时,我在控制台中获得了 Firebase 用户实例。尝试时 getSignedInUser().uid ,上面写着 Class Future<dynamic>没有实例 getter uid .如果在我的功能范围内,我打印出 mCurrentUser.uid (到控制台),我确实得到了正确的打印输出。我不想在控制台中使用它。如果在另一个文件中,我想访问,例如,当前用户的电子邮件,我想调用该函数,如 getSignedInUser().email (当函数返回该用户时)

在authentication.dart中:

getSignedInUser() async {
mCurrentUser = await FirebaseAuth.instance.currentUser();
if(mCurrentUser == null || mCurrentUser.isAnonymous){
print("no user signed in");
}
else{
return mCurrentUser;
//changing above line to print(mCurrentUser.uid) works, but that's useless
//for the purpose of this function
}
}

homescreen.dart登录后,我有一个检查当前用户的按钮:

Widget checkUserButton() {
return RaisedButton(
color: Color.fromRGBO(58, 66, 86, 1.0),
child: Text("who's signed in?", style: TextStyle(color: Colors.white)),
onPressed: () {
print(getSignedInUser().uid);
//applying change to comments in getSignedInUser() function above
//changes this to just call getSignedInUser()
},
);
}

我希望这会带回来自 getSignedInUser() 的用户函数并允许我使用 Firebase Auth 类中的那些内置函数。但是,那些不会像预期的那样自动填充,只是抛出如上所述的运行时错误。我只是将它打印到控制台以查看我的输出作为测试。一旦我知道我正在访问诸如用户 ID 之类的字段,那么我就可以使用该信息从任何其他屏幕执行我需要的操作(只要我导入 authentication.dart)。感谢您的帮助

最佳答案

您忘记了您的 getSignedInUser函数是一个异步函数,因此它在您的情况下返回一个 Future 对象 Future<FirebaseUser>实例。你正在尝试阅读 uid来自 Future 对象实例的属性,这就是您收到错误消息的原因:'Future' 没有实例 getter 'uid'

要解决这个问题,您只需要 await读取正确结果的函数。

Widget checkUserButton() {
return RaisedButton(
color: Color.fromRGBO(58, 66, 86, 1.0),
child: Text("who's signed in?", style: TextStyle(color: Colors.white)),
onPressed: () async { // make on pressed async
var fbUser = await = getSignedInUser(); // wait the future object complete
print(fbUser.uid); // gotcha!
//applying change to comments in getSignedInUser() function above
//changes this to just call getSignedInUser()
},
);
}

关于firebase - 如何返回 firebase 用户以访问某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55601249/

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