skip to Main Content

I want to print a data from patient information inside the user data collection with a current user id. I have successfully printed the result out but I don’t know how to pass it to my widget. I cannot use list view because I want to print just one field.

my firebase

enter image description here

This is the async function that I have made

retrieveSubCol() async {
     String fullName = '';
     await FirebaseFirestore.instance.collection('userData').get().then((value) {
      value.docs.forEach((result) {
        FirebaseFirestore.instance
            .collection('userData')
            .doc(result.id)
            .collection('patient_information')
            .get()
            .then((user) {
          user.docs.forEach((element) {
            print(element.data());
            fullName = element.data()['name'];
          });
        });
      });
    });
   }

This is my widget and future builder, I want to print the full Name in the Ali text:

Widget build(BuildContext context) {
       return FutureBuilder(
        future: retrieveSubCol(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Scaffold(
              body: SingleChildScrollView(
                padding: EdgeInsets.only(top: 30),
                child: Container(
                  padding: const EdgeInsets.all(10),
                  child: Column(
                    children: [
                      Text(
                        "Profile",
                        style: TextStyle(
                          fontSize: 35,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      SizedBox(
                        width: 120,
                        height: 120,
                        child: ClipRRect(
                            borderRadius: BorderRadius.circular(100),
                            child: Image(
                              image: AssetImage('images/doctor1.jpg'),
                            )),
                      ),
                      const SizedBox(height: 10),
                      Text('Ali',
                          style: Theme.of(context).textTheme.headlineMedium),
                      Text('About',
                          style: Theme.of(context).textTheme.bodyMedium),
                      const SizedBox(height: 20),
                      SizedBox(
                        child: ElevatedButton(
                          onPressed: () {},
                          child: const Text(
                            'Edit Profile',
                            style: TextStyle(
                                color: Color.fromARGB(255, 255, 255, 255)),
                          ),
                        ),
                      ),

I have tried to use return but still not work. Or maybe is there something wrong with my future builder?

My field in the patient_information subcollection:

patient information subcollection field

2

Answers


  1. Chosen as BEST ANSWER

    Finally! I have found an answer!

    This is the future function, before that I declared all the variables as String:

      Future retrieveSubCol() async {
        await FirebaseFirestore.instance.collection('userData').get().then((value) {
          value.docs.forEach((result) {
            FirebaseFirestore.instance
                .collection('userData')
                .doc(FirebaseAuth.instance.currentUser!.uid)
                .collection('patient_information')
                .get()
                .then((user) {
              user.docs.forEach((element) {
                print(element.data());
                setState(() {
                  fullname = element.data()['name'];
                  icNo = element.data()['icNo'];
                  age = element.data()['age'];
                  birthDate = element.data()['birthDate'];
                  email = element.data()['email'];
                  noPhone = element.data()['phoneNo'];
                  address = element.data()['address'];
                  history = element.data()['medicalHistory'];
                  insurance = element.data()['medicalInsurance'];
                  panel = element.data()['panelClinic'];
                });
              });
            });
          });
        });
      }
    

    I declared it in inistate since I used setState:

    void initState() {
     super.initState();
     retrieveSubCol();
    }
    

    Then I used StreamBuilder:

    
    return StreamBuilder(
            stream: FirebaseAuth.instance.authStateChanges(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Scaffold(
                  body: SingleChildScrollView(
                    padding: EdgeInsets.only(top: 30),
                    child: Container(
                      padding: const EdgeInsets.all(10),
                      child: Column(
                        children: [
                          Text(
                            "Profile",
                            style: TextStyle(
                              fontSize: 35,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          SizedBox(
                            width: 120,
                            height: 120,
                            child: ClipRRect(
                                borderRadius: BorderRadius.circular(100),
                                child: Image(
                                  image: AssetImage('images/doctor1.jpg'),
                                )),
                          ),
                          const SizedBox(height: 10),
                          Text(fullname!,
                              style: Theme.of(context).textTheme.bodyMedium),
                          Text('About',
                              style: Theme.of(context).textTheme.bodyMedium),
    

    All printed correctly according to my data!


  2. If you want to display just the name field from the first document in the patient_information subcollection, you can do:

    Widget build(BuildContext context) {
     return FutureBuilder(
      future: retrieveSubCol(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          var querySnapshot = snapshot.data!; //⒈ Get the data
          var docs = querySnapshot.docs;      //⒉ Get the documents
          var firstDoc = docs[0];             //⒊ Get the first document
          var name = firstDoc.get("name");    //⒋ Get the name field from it
          return Text("Name: $name")          //⒌ Render it as a Text widget
        }
      }
    

    Documentation is inline in the code above.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search