Home > Software engineering >  Retrieve one field from firebase and display it in a Text Widget
Retrieve one field from firebase and display it in a Text Widget

Time:11-20

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)),

Any tips? Image with the database structure

CodePudding user response:

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/

CodePudding user response:

Add this in your initState

so, the data will be fetched before the build function run and you can acces "firstName" inside Text widget

  @mustCallSuper
  void initState()async {
   await DocumentReference userName = FirebaseFirestore.instance
      .collection('users')
      .doc(FirebaseAuth.instance.currentUser!.uid);
userName.snapshots().listen((snapshot) {
      var firstName = snapshot.docs["firstName"];
       });
    super.initState();
     }

if you put the full code i will run the code and show the desired output in my emulator

Thank you

  • Related