gpt4 book ai didi

flutter - 即时通讯应用上的消息顺序不正确

转载 作者:行者123 更新时间:2023-12-03 13:30:34 26 4
gpt4 key购买 nike

我刚刚基于教程完成了这个基本的聊天应用程序,但是我想从底部开始的消息并不总是如此。

当我删除,保存并重新添加时,在此行上反转:

final messages = snapshot.data.documents.reversed;

那么它似乎可以正确地重新排序,但是下一条消息又是随机的。

唯一的区别是,我使用的是更新版本的Firebase插件。
  • -firebase_core:0.4.0 + 8,教程是^ 0.3.4
    -firebase_auth:0.14.0 + 1,教程为^ 0.8.4 + 4
    -cloud_firestore:0.12.9,教程为^ 0.9.13 + 1

  • //消息流代码
    class MessagesStream extends StatelessWidget {

    @override
    Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
    stream: _firestore.collection('messages').snapshots(),
    builder: (context, snapshot) {
    if (!snapshot.hasData) {
    return Center(
    child: CircularProgressIndicator(
    backgroundColor: Colors.lightBlue,
    ),
    );
    }
    final messages = snapshot.data.documents.reversed;
    List<MessageBubble> messageBubbles = [];
    for (var message in messages) {
    final messageText = message.data['text'];
    final messageSender = message.data['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(vertical: 20.0, horizontal: 10.0),
    children: messageBubbles,
    ),
    );
    },
    );
    }
    }

    除了随机顺序外,一切正常,消息保存在Firebase中。也许我需要添加时间码或其他东西才能使其正常工作。

    任何帮助表示赞赏-谢谢。

    最佳答案

    应用此代码后,就像Angela在她的类(class)视频中一样删除Firebase中的数据库,然后重新启动应用程序。您的应用程序将运行。另外,在代码中,我还添加了有关您必须添加的内容的说明。仅添加它们。
    我遇到了同样的问题,因此我在编码人员的帮助下解决了这个问题。因此,它也将在您的代码中工作。

    import 'package:flutter/material.dart';
    import 'package:flash_chat/constants.dart';
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:cloud_firestore/cloud_firestore.dart';

    final _fireStore = Firestore.instance;
    FirebaseUser loggedInUser;

    class ChatScreen extends StatefulWidget {
    static String chatScreen = 'ChatScreenpage1';
    @override
    _ChatScreenState createState() => _ChatScreenState();
    }

    class _ChatScreenState extends State<ChatScreen> {
    final messageTextEditingController = TextEditingController();
    String messageText;

    final _auth = FirebaseAuth.instance;

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

    void getUserDetail() async {
    try {
    final createdUser = await _auth.currentUser();
    if (createdUser != null) {
    loggedInUser = createdUser;
    }
    } catch (e) {
    print(e);
    }
    }

    @override
    Widget build(BuildContext context) {
    return Scaffold(
    appBar: AppBar(
    leading: null,
    actions: <Widget>[
    IconButton(
    icon: Icon(Icons.close),
    onPressed: () {

    _auth.signOut();
    Navigator.pop(context);
    }),
    ],
    title: Text('⚡️Chat'),
    backgroundColor: Colors.lightBlueAccent,
    ),
    body: SafeArea(
    child: Column(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: <Widget>[
    StreambuilderClass(),
    Container(
    decoration: kMessageContainerDecoration,
    child: Row(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
    Expanded(
    child: TextField(
    controller: messageTextEditingController,
    onChanged: (value) {
    messageText = value;
    },
    decoration: kMessageTextFieldDecoration,
    ),
    ),
    FlatButton(
    onPressed: () {
    messageTextEditingController.clear();
    _fireStore.collection('messages').add({
    'sender': loggedInUser.email,
    'text': messageText,
    'time': FieldValue.serverTimestamp() //add this
    });
    },
    child: Text(
    'Send',
    style: kSendButtonTextStyle,
    ),
    ),
    ],
    ),
    ),
    ],
    ),
    ),
    );
    }
    }

    class StreambuilderClass extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
    stream: _fireStore
    .collection('messages')
    .orderBy('time', descending: false)//add this
    .snapshots(),
    builder: (context, snapshot) {
    if (!snapshot.hasData) {
    return Center(
    child: CircularProgressIndicator(
    backgroundColor: Colors.blueAccent,
    ),
    );
    }
    final messages = snapshot.data.documents.reversed;
    List<MessageBubble> messageBubbles = [];
    for (var message in messages) {
    final messageText = message.data['text'];
    final messageSender = message.data['sender'];
    final messageTime = message.data['time'] as Timestamp; //add this
    final currentUser = loggedInUser.email;

    final messageBubble = MessageBubble(
    sender: messageSender,
    text: messageText,
    isMe: currentUser == messageSender,
    time: messageTime, //add this
    );

    messageBubbles.add(messageBubble);
    }

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

    class MessageBubble extends StatelessWidget {
    final String text;
    final String sender;
    final bool isMe;
    final Timestamp time; // add this

    MessageBubble({this.text, this.sender, this.isMe, this.time}); //add the variable in this constructor
    @override
    Widget build(BuildContext context) {
    return Padding(
    padding: EdgeInsets.all(10.0),
    child: Column(
    crossAxisAlignment:
    isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
    children: <Widget>[
    Text(
    ' $sender ${DateTime.fromMillisecondsSinceEpoch(time.seconds * 1000)}',// add this only if you want to show the time along with the email. If you dont want this then don't add this DateTime thing
    style: TextStyle(color: Colors.black54, fontSize: 12),
    ),
    Material(
    color: isMe ? Colors.blueAccent : Colors.white,
    borderRadius: isMe
    ? BorderRadius.only(
    topLeft: Radius.circular(30),
    bottomLeft: Radius.circular(30),
    bottomRight: Radius.circular(30))
    : BorderRadius.only(
    topRight: Radius.circular(30),
    bottomLeft: Radius.circular(30),
    bottomRight: Radius.circular(30)),
    elevation: 6,
    child: Padding(
    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
    child: Text(
    text,
    style: TextStyle(
    fontSize: 20, color: isMe ? Colors.white : Colors.black),
    ),
    ),
    ),
    ],
    ),
    );
    }
    }

    关于flutter - 即时通讯应用上的消息顺序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57584317/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com