0

I'm getting null value in flutter build method for this code.

  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");
    }
  }

output is

Performing hot restart...

Restarted application in 759ms. null {entries: 3, name: xmr} vraj Username is xmr


1
  • can you please show us MyFirebaseAuth ? and try to remove setState from the initstate Commented Dec 1, 2019 at 5:44

1 Answer 1

1

The getUserName is future so the method should be

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");
}
}

And also make sure to use setState inside the getUserName() instead of initState

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.