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

Any tips? Image with the database structure

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
Ad