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

如何返回firebase用户以访问某些元素,firebase,dart,flutter,firebase-authentication,Firebase,Dart,Flutter,Firebase Authentication,我试图在一个文件中编写一个函数,以在其他文件中获取当前登录用户 现在,我只是让它返回用户,然而,当调用该函数时,我在控制台中得到Firebase用户的实例。当尝试getSignedUser().uid时,它说类Future没有实例getteruid。如果在我的函数中,我打印出mCurrentUser.uid(到控制台),我会得到正确的打印输出。我不想把它放在控制台里。如果在另一个文件中,我想访问当前用户的电子邮件,我想调用该函数,如getSignedInUser().email(当函数返回该用户

我试图在一个文件中编写一个函数,以在其他文件中获取当前登录用户

现在,我只是让它返回用户,然而,当调用该函数时,我在控制台中得到Firebase用户的实例。当尝试
getSignedUser().uid
时,它说类
Future
没有实例getter
uid
。如果在我的函数中,我打印出
mCurrentUser.uid
(到控制台),我会得到正确的打印输出。我不想把它放在控制台里。如果在另一个文件中,我想访问当前用户的电子邮件,我想调用该函数,如
getSignedInUser().email
(当函数返回该用户时)

在身份验证中。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
  }
}
在登录后的
主屏幕.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()
      },
    );
  }

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

您忘记了您的
getSignedUser
函数是一个异步函数,因此它在您的情况下返回一个Future对象,即
Future
实例。您正在尝试从未来的对象实例读取
uid
属性,这就是您收到错误消息的原因: “Future”没有实例获取程序“uid”

要解决这个问题,只需等待函数读取正确的结果

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()
      },
    );
  }

啊哈!非常感谢你。那是丢失的一块