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

问题描述 投票:0回答:1

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

现在,我只是让它返回用户,但是,在调用该函数时,我在控制台中获得了Firebase用户实例。在尝试使用getSignedInUser()。uid时,它说类'Future'没有实例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)。谢谢你的帮助

firebase dart flutter firebase-authentication
1个回答
1
投票

你忘了你的getSignedInUser函数是一个异步函数,所以它返回你的情况下的一个Future对象一个Future<FirebaseUser>实例。您正在尝试从Future对象实例读取uid属性,这就是您收到错误消息的原因:'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()
      },
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.