Reputation: 632
I want to get the user name that is currently logged in from firebase's real-time databse. I stored the information on signing up the user. I used Future Builder and it is also printing the name on the terminal but I am unable to display the username on Navigation drawer. Kindly help me out where I am doing wrong as I am new to Flutter. Thank you in advance!
Code for function:
Future<String> getUsername() async {
final ref = FirebaseDatabase.instance.reference();
User cuser = await firebaseAuth.currentUser;
ref.child('User_data').child(cuser.uid).once().then((DataSnapshot snap) {
final String userName = snap.value['name'].toString();
print(userName);
return userName;
});
}
Code where i have used Builder:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FutureBuilder<String>(
future: getUsername(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(
snapshot.data,
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 13,
color: const Color(0xff000000),
fontWeight: FontWeight.w700,
),
textAlign: TextAlign.left,
);
} else {
return Text(
"Loading data...",
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 13,
color: const Color(0xff000000),
fontWeight: FontWeight.w700,
),
textAlign: TextAlign.left,
);
}
},
),
Image of my Screen:
My Database where information is stored:
I want to get this 2nd user's name: Hania Salman from the database
Upvotes: 0
Views: 1651
Reputation: 431
You aren't returning the username from your getUsername() function. The return userName you have written is for the function inside then() not for getUsername(). So it should be like this
Future<String> getUsername() async {
final ref = FirebaseDatabase.instance.reference();
User cuser = await firebaseAuth.currentUser;
return ref.child('User_data').child(cuser.uid).once().then((DataSnapshot snap) {
final String userName = snap.value['name'].toString();
print(userName);
return userName;
});
}
Upvotes: 1