Fetching values from Firebase returning null when displaying to TextFormField Flutter

Solution for Fetching values from Firebase returning null when displaying to TextFormField Flutter
is Given Below:

  • I have fetched the information from Firebase and I am able to print it in the console. But when I try to pass that value to TextFormField as an initialValue it is displaying null.
  • Console output
I/flutter (13599): lavsharmaa
// fetching the value from the firestore
  Future<void> _getUserName() async {
    final User user = _auth.currentUser;
    final uid = user.uid;
    FirebaseFirestore.instance.collection('users').doc(uid).get().then((value) {
      setState(() {
        username = value.data()['userName'].toString();
      });
      print(username);
    });
  }
...
@override
...
// displaying it in TextFormField
TextFormField(
    initialValue: '$username',
    keyboardType: TextInputType.emailAddress,
    onChanged: (value) {
         setState(() {
              username = value;
            });
          },
   style: TextStyle(
       fontFamily: 'Montserrat',
       fontSize: 16,
      ),
     ),

enter image description here

The problem is that the function _getUserName() is async and by that, the value username is updated after the build. Instead of initialValue you can use a TextEditingController and change the value of the TextFormField as you fetch the username from Firestore.

For Example:

_controller.value = TextEditingValue(
    text: username.toString(),
    selection: TextSelection.fromPosition(
      TextPosition(offset: username.toString().length),
    ),
  );