【问题标题】:How do I return a firebase user to access certain elements如何返回 firebase 用户以访问某些元素
【发布时间】:2019-04-09 20:59:17
【问题描述】:

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

现在,我只是让它返回用户,但是,当调用该函数时,我在控制台中获得了 Firebase 用户的实例。当尝试getSignedInUser().uid 时,它说 Class Future<dynamic> has no instance 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】:

    您忘记了您的 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()
          },
        );
      }
    

    【讨论】:

    • 啊哈!非常感谢。那是缺失的部分
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2020-11-23
    相关资源
    最近更新 更多