Mohamed Shaheen
Mohamed Shaheen

Reputation: 663

get firebase data without streambuilder

This is how I get data using stream builder from firebase

StreamBuilder<QuerySnapshot>(
            stream: Firestore.instance.collection('profile').snapshots(),
            builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
              if (!snapshot.hasData) return const Text('Loading...');
              final int messageCount = snapshot.data.documents.length;
              return ListView.builder(
                  shrinkWrap: true,
                  itemCount: messageCount,
                  itemBuilder: (_, int index) {
                    final DocumentSnapshot document = snapshot.data.documents[index];
                    return Container();}
              );
            },
          ),

My question is, How to get a collection list data to a list inside initstate() maybe using a function

List data=new List();
    @override
      void initState() {
        super.initState();

        //here
      }

Upvotes: 4

Views: 2863

Answers (1)

Jay Mungara
Jay Mungara

Reputation: 7148

Just do as follow inside your stateful class to fetch the data,

bool isFetching=false;
List<String> dataList=[];

@override
void initState() {
super.initState();

getGroupsData();
}

getGroupsData() {
setState(() {
   isFetching= true;
});

databaseReference
    .collection("profile")
    .getDocuments()
    .then((QuerySnapshot snapshot) {
    snapshot.documents.forEach((f) => dataList.add[f.data["name"]));

   setState(() {
      isFetching= false;
   });
  });
}

@override
  Widget build(BuildContext context) {
    return Scaffold(
    body: Center(
    child : isFetching ?
            CircularProgressIndictaor()
            : dataList!=null && dataList.length >0 
            ? ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                               return Text(dataList[index]);
                               }
                  )
            : Text("No Data"),
      )
    );
}

Upvotes: 2

Related Questions