Ad
Retrieve One Field From Firebase And Display It In A Text Widget
I am retrieving a user's first name from firestore, store it in a variable and then trying to display it using a Text Widget. The database query works for sure because I print it's outcome. On the other hand, the variable used to store the data is used in the Text widget but it's not displaying anything.
homepage.dart
//get the specific document I need
DocumentReference userName = FirebaseFirestore.instance
.collection('users')
.doc(FirebaseAuth.instance.currentUser!.uid);
//Variable used to store the name
String firstName = '';
@override
Widget build(BuildContext context) {
//Get specific field from a document
userName.get().then((DocumentSnapshot ds) {
firstName = ds['firstName'];
print(firstName);
});
return Scaffold(
appBar: AppBar(
title: const Text('Homepage'),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.only(
top: 20,
),
child: Text(firstName)),
Ad
Answer
call it in init state; otherwise, you can call it by using FutureBuilder
or StreamBuilder
@override
void initState() {
super.initState();
userName.get().then((DocumentSnapshot ds) {
firstName = ds['firstName'];
print(firstName);
});
}
Updated
FutureBuilder<DocumentSnapshot>(
future: userName.get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.hasData && !snapshot.data!.exists) {
return Text("Document does not exist");
}
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
return Text("Full Name: ${data['firstName']}");
}
return Text("loading");
},
)
For more, you can read this article https://firebase.flutter.dev/docs/firestore/usage/
Ad
source: stackoverflow.com
Related Questions
- → How can I query Firebase for an equalTo boolean parameter?
- → How can I access nested data in Firebase with React?
- → Firebase simple blog (confused with security rules)
- → Removing item in Firebase with React, re-render returns item undefined
- → AngularJS Unknown Provider Error (Firebase & AngularFire)
- → How do you pass top level component state down to Routes using react-router?
- → "this" is null in firebase query function in reactjs
- → Angular Module Failed to Load
- → Multiple dex files define Lcom/google/android/gms/internal/zzrx;
- → Joining Firebase tables in React
- → How can I make add firepad to my reactjs project?
- → How to use Cloud Functions for Firebase to prerender pages for SEO?
- → React.js component has null state?
Ad