【问题标题】:firebase firestore chat timestamp order not working corectlyfirebase firestore 聊天时间戳顺序无法正常工作
【发布时间】:2021-10-23 21:54:46
【问题描述】:

下面是我的代码,我在颤振中进行了一次聊天,它应该按时间戳排序,但它似乎仍然是随机的,在 Firebase 上它正在 json 中记录正确的时间戳,我认为我用firestore.collection 通过电话订购。附件图片显示了他们应该订购的消息 1-6

import 'package:flutter/material.dart';
import 'package:bardsf/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
late String messageText;


class BodyBuildingChat extends StatefulWidget {
  static const String id = 'body_building_chat';
  @override
  _BodyBuildingChatState createState() => _BodyBuildingChatState();
}

class _BodyBuildingChatState extends State<BodyBuildingChat> {
  final messageTextController = TextEditingController();
  final _firestore = FirebaseFirestore.instance;
  final _auth = FirebaseAuth.instance;
  late User loggedInUser;
  @override
  void initState() {

    super.initState();
    getCurrentUser();
  }
  void getCurrentUser() async {
    try {
      final user = await _auth.currentUser;
      if (user != null) {
        loggedInUser = user;
        print(loggedInUser.email);
      }
    } catch (e) {
      print (e);
    }
  }

  // void getMessages() async{
  // final messages = await _firestore.collection('messages').get();
  // for (var message in messages.docs) {
  //   print(message.data().cast());
  // }
  // }
  void messagesStream() async {
    await for( var snapshot in _firestore.collection('bodybuilding').orderBy('timestamp').snapshots()) {
      for (var message in snapshot.docs) {
        print(message.data().cast());
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: null,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.close),
              onPressed: () {
                messagesStream();
                _auth.signOut();
                Navigator.pop(context);
              }),
        ],
        title: Text('????Body Building'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            StreamBuilder<QuerySnapshot>(
              stream: _firestore.collection('bodybuilding').snapshots(),
              builder: (context, snapshot){
                List<MessageBubble> messageBubbles = [];
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(
                      backgroundColor: Colors.lightBlueAccent,
                    ),
                  );

                }
                final messages = snapshot.data!.docs.reversed;

                for (var message in messages) {
                  final messageText = message['text'];
                  final messageSender = message['sender'];

                  final currentUser = loggedInUser.email;


                  final messageBubble = MessageBubble(
                    sender: messageSender,
                    text: messageText,
                    isMe: currentUser == messageSender,
                  );

                  messageBubbles.add(messageBubble);
                }


                return Expanded(
                  child: ListView(
                    reverse: true,
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                    children: messageBubbles,
                  ),
                );

              },


            ),
            Container(
              decoration: kMessageContainerDecoration,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      controller: messageTextController,
                      onChanged: (value) {
                        messageText = value;
                      },
                      decoration: kMessageTextFieldDecoration,
                    ),
                  ),
                  TextButton(
                    onPressed: () {

                      messageTextController.clear();
                      _firestore.collection('bodybuilding').add({
                        'text': messageText,
                        'sender': loggedInUser.email,
                        'timestamp': FieldValue.serverTimestamp(),
                      });
                    },
                    child: Text(
                      'Send',
                      style: kSendButtonTextStyle,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}



class MessageBubble extends StatelessWidget {


  MessageBubble({required this.sender,required this.text,required this.isMe});

  final String sender;
  final String text;
  final bool isMe;

  @override
  Widget build(BuildContext context) {
    return  Padding(
      padding: EdgeInsets.all(10.0),
      child: Column(
        crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
        children: <Widget>[
          Text(sender,
            style: TextStyle(
              fontSize: 12.0,
            ),
          ),
          Material(
            borderRadius: isMe ? BorderRadius.only(topLeft: Radius.circular(30.0),
              bottomLeft: Radius.circular(30.0),
              bottomRight: Radius.circular(30.0),
            ) : BorderRadius.only(topRight: Radius.circular(30.0),
              bottomLeft: Radius.circular(30.0),
              bottomRight: Radius.circular(30.0),
            ),

            elevation: 5.0,
            color: isMe ? Colors.lightBlueAccent : Colors.white,
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 8.0),
              child: Text('$text',
                style: TextStyle( fontSize: 15.0,
                  color: isMe ? Colors.white : Colors.black,),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    您没有使用适当的流。 改变这一行

    stream: _firestore.collection('bodybuilding').snapshots(),
    

    进入这一行

    stream: _firestore.collection('bodybuilding').orderBy('timestamp').snapshots(),
    

    您会注意到您在messagesStream 中使用了正确的流,但在StremBuilder 中却没有。

    如果这没有帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2020-11-30
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多