How can i fetch single value from Firebase real time database using a method

Viewed 63

This is my method i intend to use it to fetch data from database to a Text widget

getSnapshotData (String child){
    final User _firebaseUser = firebaseAuth.currentUser;
    databaseReference
      .child("users")
      .child(_firebaseUser.uid)
      .once()
      .then((DataSnapshot dataSnapshot) {
        return dataSnapshot.value('${child}');
      }
    );

this is my Text widget to retrieve name from the database

Text(
  'Hi,' + ' ${getSnapshotData('name')}',
   style: TextStyle(
   color: Colors.black,
   fontSize: 32,
)),

this is my Text widget to retrieve order count from the database

Text(
   getSnapshotData('orders_count').toString(),
   style: TextStyle(
   color: Colors.black,
   fontSize: 32,
)),

i have tried logging the values of orders count and name and virtually everything,

Everything seems to be ok i dont understand whats the problem i used more than three hours trying to look for a solution but failed

enter image description here

1 Answers

Use Future Builder to fetch data

create getPost() method first to return qn

Future getPosts() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore.collection("your_collecttion_name").getDocuments();
    return qn.documents;
  }

after that use, future builder to fetch data

return Container(
      child: FutureBuilder(
          future: getPosts(),
          builder: (_, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: Text("Loading..."),
              );
            } else {
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (_, index) {
                    return Column(
                         children: <Widget>[
                             Text(
                               snapshot.data[index].data['your_data']
                                .toString(),
                                style: TextStyle(
                                 fontSize: 20,
                                 fontWeight: FontWeight.w500),
                              ),]
                          ),}
                        ),
                     });
Related