1

In my code, am trying a assign a string value to an empty string and display on the page but it keeps showing null but when I print it out, it shows the value.

String fName = '';

@override
  void initState() {
    super.initState();
    getData();
  }

getData() async {
    FirebaseAuth _auth = FirebaseAuth.instance;
    User _firebaseUser = _auth.currentUser;
    print("============ MyHome ================");
    print(_firebaseUser.uid);
    _currentUser = await Database().getUserData(_firebaseUser.uid);
    if (_currentUser != null) {
      fName = _currentUser.firstName;
      print(_currentUser.firstName);
    } 
  }

database

Future<UserData> getUserData(String uid) async {
    UserData returnValue = UserData();

    try {
      DocumentSnapshot _docSnapshot =
          await _firestore.collection("users").doc(uid).get();
      returnValue.uid = uid;
      returnValue.firstName = _docSnapshot.data()["firstName"];
      returnValue.lastName = _docSnapshot.data()["lastName"];
      returnValue.userMail = _docSnapshot.data()["userMail"];
      returnValue.userType = _docSnapshot.data()["userType"];
      print("====================== on getData =============");
      print(returnValue.firstName);
    } catch (e) {
      print(e);
    }

    return returnValue;
  }

And whenever I try displaying the data it gives me null

Text("Hello, $fName"),

Please how do I do this or am I missing something

3 Answers 3

2

use setState to rebuild the widget tree with the value:

setState(() { 
fName = _currentUser.firstName;
});
Sign up to request clarification or add additional context in comments.

Comments

1

Since the getData function is async, flutter has already built the widget tree before getData finished. You'll now have to update the state using setstate.

setState(() {
   fName = _currentUser.firstName;
});

Comments

1

You need to set the new state since we have made changes to the previous state (since your getData function is async.

setState(() {
   fName = _currentUser.firstName;
});

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.