Home > Software design >  convert this into streambuilder in flutter
convert this into streambuilder in flutter

Time:12-11

I want to convert this function into Streambuilder, but somehow I could not figure out how I could do it. Any help would be greatly appreciated.

  Future getReceiverChats() async {
    var data = await FirebaseFirestore.instance
        .collection("message")
        .doc(widget.id)
        .collection("nodes")
        .orderBy("time", descending: false)
        .get();
    setState(() {
      _msgReceiverList =
          List.from(data.docs.map((doc) => Message.fromMap(doc)));
    });
  }

CodePudding user response:

StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
  .collection("message")
  .doc(widget.id)
  .collection("nodes")
  .orderBy("time", descending: false)
  .snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
  return Text("Error: ${snapshot.error}");
}
switch (snapshot.connectionState) {
  case ConnectionState.waiting:
    return Text("Loading...");
  default:
    return ListView(
      children: snapshot.data.docs.map((doc) {
        return Message.fromMap(doc);
      }).toList(),
     );
  }
 },
 ),

CodePudding user response:

Try this:

Stream<List<Message>> getReceiverChats(String id) {
    return FirebaseFirestore.instance
        .collection("message")
        .doc(id)
        .collection("nodes")
        .orderBy("time", descending: false)
        .snapshots()
        .map((QuerySnapshot query) {
      List<Message> dataList = [];
      query.docs.forEach((doc) {
        dataList
            .add(Message.fromMap(doc));
      });
      return dataList;
    });
  }

Then:

 StreamBuilder<List>(
             stream: getReceiverChats(widget.id),
             builder: (context, snapshot) {

            if (snapshot.hasData) {
              final List<Message>? dataList = snapshot.data;
              if (dataList!.isEmpty) {
                return Center(
                  child: Text('No results'),
                );
              }
              return ListView.builder(              
                  itemCount: dataList.length,
                  itemBuilder: (context, index) {
                    return MyWidget(dataList[index]);
                  });
            }

            if (snapshot.connectionState == ConnectionState.done) {
              if (!snapshot.hasData) {
                return Center(
                  child: Text('No results'),
                );
              }
            }
            return const Center(
              child: CircularProgressIndicator(),
            );
})

  • Related