繁体   English   中英

在 flutter 中将其转换为 streambuilder

[英]convert this into streambuilder in flutter

我想将此function转换为Streambuilder ,但不知何故我不知道该怎么做。 任何帮助将不胜感激。

  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)));
    });
  }

试试这个:

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;
    });
  }

然后:

 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(),
            );
})

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(),
     );
  }
 },
 ),

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM