【问题标题】:How to get last message from message collection in flutter如何从颤动的消息集合中获取最后一条消息
【发布时间】:2021-03-02 12:16:08
【问题描述】:

当我试图让最后一条消息显示在下面的小部件中时,当我的消息集合中的数据很明显时,有人可以帮助为什么这段代码不返回任何消息。

![消息集合][1]

![1]:https://i.stack.imgur.com/uGJgV.png

  final ChatMethods chatMethods = ChatMethods();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(
          widthFactor: 5,
          child: Text(
            'Message',
            style: mystyle(
              20.0,
              Style.Colors.titleColor,
            ),
          ),
        ),
      ),
      body: StreamBuilder(
        stream: chatMethods.fetchLastMessageBetween(
            senderId: firebaseAuth.currentUser.uid, receiverId: widget.uid),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasData) {
            
            var docList = snapshot.data.docs;

            if (docList.isNotEmpty) {
              Message message = Message.fromMap(docList.last.data());
              return SizedBox(
                width: MediaQuery.of(context).size.width * 0.6,
                child: Text(
                  message.message,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 14,
                  ),
                ),
              );
            }
            return Text(
              "No Message",
              style: TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
            );
          }
          return Text(
            "..",
            style: TextStyle(
              color: Colors.grey,
              fontSize: 14,
            ),
          );
        },
      ),
    );
  }
}

【问题讨论】:

标签: javascript java flutter flutter-layout


【解决方案1】:

是的,有。降序和限制为 1 将为您提供结果。

this.historyRef = afs.collection<History>('history', ref => ref.orderBy('date', 'desc').limit(1));
this.history = this.historyRef.snapshotChanges().map(actions => {
    return actions.map(a => {
        const data = a.payload.doc.data() as Hisotory;
        const docId = a.payload.doc.id;
        return { docId, ...data };
    });
});

原始答案来自:Get last created document in a Firebase Firestore collection

【讨论】:

  • 我看不懂代码,因为我正在使用流生成器来获取数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 2019-12-26
  • 2017-05-24
  • 2016-10-12
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
相关资源
最近更新 更多