在异步方法抖动后将空值获取到变量

时间:2019-12-01 05:39:45

标签: firebase flutter dart google-cloud-firestore firebase-authentication

在此代码的flift构建方法中,我得到了空值。

  String userEmail;
  var data;
  String userName;
  @override
  void initState(){
      setState(() {
        getUserName();
        print(userName);
      });
    super.initState();
  }

  void getUserName() async {
    MyFirebaseAuth myFirebaseAuth = MyFirebaseAuth();
    userEmail =await myFirebaseAuth.getUser();
    if (userEmail == null){
      print("no user");
    }
    else{
      data =await fb.firestore().collection('users').doc(userEmail).get().then((onValue){
        return onValue.data();
      });
      print(data);
      print(data['name']);
      userName = data['name'];
      print("Username is $userName");
    }
  }

输出是

执行热重启...

在759毫秒内重新启动应用程序。 空值 {项目:3,名称:xmr} Vraj 用户名是xmr


1 个答案:

答案 0 :(得分:1)

getUserName是将来的,因此方法应为

Future<void>getUserName() async {
MyFirebaseAuth myFirebaseAuth = MyFirebaseAuth();
userEmail =await myFirebaseAuth.getUser();
if (userEmail == null){
  print("no user");
}
else{
  data =await fb.firestore().collection('users').doc(userEmail).get().then((onValue){
    return onValue.data();
  });
  print(data);
  print(data['name']);
  userName = data['name'];
  print("Username is $userName");
}
}

还要确保在getUserName()中使用setState而不是initState