uni-app | A cross-platform framework using Vue.js | Chat library

 by   dcloudio JavaScript Version: v2.0.2-alpha-3071220230331001 License: Apache-2.0

kandi X-RAY | uni-app Summary

uni-app is a JavaScript library typically used in Messaging, Chat, Vue applications. uni-app has no vulnerabilities, it has a Permissive License and it has medium support. However uni-app has 24 bugs. You can install using 'npm i vue-cli-plugin-enn' or download it from GitHub, npm.
uni-app 是使用 Vue 语法开发小程序、H5、App的统一框架
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        uni-app has a medium active ecosystem.
                        summary
                        It has 37882 star(s) with 3436 fork(s). There are 502 watchers for this library.
                        summary
                        It had no major release in the last 6 months.
                        summary
                        There are 993 open issues and 2821 have been closed. On average issues are closed in 200 days. There are 22 open pull requests and 0 closed requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of uni-app is v2.0.2-alpha-3071220230331001
                        uni-app Support
                          Best in #Chat
                            Average in #Chat
                            uni-app Support
                              Best in #Chat
                                Average in #Chat

                                  kandi-Quality Quality

                                    summary
                                    uni-app has 24 bugs (0 blocker, 0 critical, 2 major, 22 minor) and 5 code smells.
                                    uni-app Quality
                                      Best in #Chat
                                        Average in #Chat
                                        uni-app Quality
                                          Best in #Chat
                                            Average in #Chat

                                              kandi-Security Security

                                                summary
                                                uni-app has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                uni-app code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                uni-app Security
                                                  Best in #Chat
                                                    Average in #Chat
                                                    uni-app Security
                                                      Best in #Chat
                                                        Average in #Chat

                                                          kandi-License License

                                                            summary
                                                            uni-app is licensed under the Apache-2.0 License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            uni-app License
                                                              Best in #Chat
                                                                Average in #Chat
                                                                uni-app License
                                                                  Best in #Chat
                                                                    Average in #Chat

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        uni-app releases are not available. You will need to build from source code and install.
                                                                        summary
                                                                        Deployable package is available in npm.
                                                                        summary
                                                                        uni-app saves you 1387 person hours of effort in developing the same functionality from scratch.
                                                                        summary
                                                                        It has 3105 lines of code, 0 functions and 1174 files.
                                                                        summary
                                                                        It has low code complexity. Code complexity directly impacts maintainability of the code.
                                                                        uni-app Reuse
                                                                          Best in #Chat
                                                                            Average in #Chat
                                                                            uni-app Reuse
                                                                              Best in #Chat
                                                                                Average in #Chat
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
                                                                                  Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  uni-app Key Features

                                                                                  A cross-platform framework using Vue.js

                                                                                  uni-app Examples and Code Snippets

                                                                                  No Code Snippets are available at this moment for uni-app.
                                                                                  Community Discussions

                                                                                  Trending Discussions on Chat

                                                                                  react-native-gifted-chat How to send on pressing return
                                                                                  chevron right
                                                                                  Mongodb Mongoose sort and paginate chat messages
                                                                                  chevron right
                                                                                  Testproject Messager with Flutter using Peer-to-Peer Technology
                                                                                  chevron right
                                                                                  How does the disconnect event works in socket.io?
                                                                                  chevron right
                                                                                  Perform action on seen/unseen messages with socket.io
                                                                                  chevron right
                                                                                  Ngfor doesn't actualize on reloading page (Angular + RXJS)
                                                                                  chevron right
                                                                                  BrokenPipeError on socket
                                                                                  chevron right
                                                                                  How to handle thousands of messages in a real-time group chat with Firestore?
                                                                                  chevron right
                                                                                  How to get information from a client socket and display information on a server?
                                                                                  chevron right
                                                                                  all messages time stamps keep updating to current time when a message is sent
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  react-native-gifted-chat How to send on pressing return
                                                                                  Asked 2022-Feb-21 at 11:33

                                                                                  How do I make the return button on the mobile keyboard send the message instead of creating a new line? I tried using onSubmitEditing in the textInputProps but couldn't get it to work.

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-21 at 11:33

                                                                                  You need to implement your own ChatComposer and pass the onSubmitEditing prop in the textInputProps in there. In order to prevent keyboard dismiss you also need to set blurOnSubmit to false.

                                                                                  const [messages, setMessages] = useState([])
                                                                                  
                                                                                  
                                                                                  const onSend = useCallback((messages = []) => {
                                                                                      setMessages((previousMessages) => GiftedChat.append(previousMessages, messages))
                                                                                  }, [])
                                                                                  
                                                                                  const ChatComposer = (
                                                                                      props: ComposerProps & {
                                                                                        onSend: SendProps["onSend"]
                                                                                        text: SendProps["text"]
                                                                                      }
                                                                                  ) => {
                                                                                      return (
                                                                                         {
                                                                                              if (props.text && props.onSend) {
                                                                                                props.onSend({ text: props.text.trim() }, true)
                                                                                              }
                                                                                            },
                                                                                          }}
                                                                                        />
                                                                                      )
                                                                                   }
                                                                                  
                                                                                  return (
                                                                                      
                                                                                    )
                                                                                  

                                                                                  If you want to remove the default send button from the text input field on the right, you need to pass a custom renderSend button, which could be empty, e.g.

                                                                                  renderSend={() => {}}
                                                                                  

                                                                                  Notice, that I have tested all of the above on iOS only. Android might behave differently.

                                                                                  Source https://stackoverflow.com/questions/71203028

                                                                                  QUESTION

                                                                                  Mongodb Mongoose sort and paginate chat messages
                                                                                  Asked 2022-Feb-07 at 14:43

                                                                                  I am making a chat app where 10 messages are loaded per page. The messages are sorted from oldest to latest, so the new messages come in bottom and old messages are in top. I tried to use skip() and limit() methods it didnt work.

                                                                                  let count = page*10
                                                                                  
                                                                                  MessageModel.find(find_query).sort({createdAt: 'asc'}).skip(count-10).limit(10).exec();

                                                                                  for example:

                                                                                  let these be my messages sorted oldest to newest: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

                                                                                  the above query returns the data like this in 1st page: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

                                                                                  2nd page : ["11", "12"]

                                                                                  but I want it to return

                                                                                  in 1st page: ["3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

                                                                                  in 2nd page: ["1", "2"]

                                                                                  EDIT: I tried sorting it into descending and reversing, this seemed to fix the issue.

                                                                                  let count = page*10
                                                                                  
                                                                                  const messages = await MessageModel.find(find_query).sort({createdAt: 'desc'}).skip(count-10).limit(10).exec();
                                                                                  
                                                                                  const re_messages = messages.reverse()

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-07 at 14:43

                                                                                  Since you want to display messages 3 to 12 first, you need to sort using 'desc' instead of 'asc', so as to get the newest messages first. This will give you ["12", "11", ... "4", "3"]. Now all you have to do is to invert this array to get ["3", "4", ... "11", "12"]:

                                                                                  let count = page*10
                                                                                  
                                                                                  let messages = await MessageModel
                                                                                                          .find(find_query)
                                                                                                          .sort({createdAt: 'desc'}) // get the latest ones
                                                                                                          .skip(count-10)
                                                                                                          .limit(10)
                                                                                                          .exec()
                                                                                                          .lean(); // Get a simple array
                                                                                  
                                                                                  messages.reverse(); // ["3", "4", ... "11", "12"]
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71020221

                                                                                  QUESTION

                                                                                  Testproject Messager with Flutter using Peer-to-Peer Technology
                                                                                  Asked 2022-Jan-27 at 14:18

                                                                                  I'm working on a Testproject, where I want to exchange information via peer-to-peer from one Mobile device to another.

                                                                                  My goal is to make a little chat widget, where when you post a message, you can see it on all devices, which are connected, a bit like this: So if I have one Mobile device, where I send the message, it's seen by all devices.

                                                                                  The reason why I'm asking for help here, is because I've looked around and found two options for peer-to-peer in Flutter: A faulty example of a peer-to-peer connection in Flutter, with practically no documentation

                                                                                  A better-documented example of peer-to-peer connection in Flutter, which also doesn't seem to work.

                                                                                  According to some people, the first option doesn't even work anymore. I've tried both and neither of them managed to achieve what I wanted. It's possible that I don't understand the difference between them 100%.

                                                                                  With this I don't even know really, how to write the Dart/Flutter code, to test the connection between two devices.

                                                                                  I have experience with using Sockets and socketstreams on Java, where one device would send something into the socket stream and the other read it out of the socket stream, but there one device was server and one client.

                                                                                  It would really help me if you could write a simple model, where this peer-to-peer connection works. Because the "documentation" available isn't helping me at all.

                                                                                  Here is the non functioning code, which I have so far

                                                                                  import 'dart:async';
                                                                                  import 'dart:convert';
                                                                                  import 'dart:io';
                                                                                  import 'dart:math';
                                                                                  import 'package:flutter/material.dart';
                                                                                  import 'package:nearby_connections/nearby_connections.dart';
                                                                                  import 'package:permission_handler/permission_handler.dart';
                                                                                  
                                                                                  final String userName = "1";
                                                                                  final Strategy strategy = Strategy.P2P_CLUSTER;
                                                                                  
                                                                                  class peerwidget extends StatefulWidget {
                                                                                    @override
                                                                                    _peerwidgetState createState() => _peerwidgetState();
                                                                                  }
                                                                                  
                                                                                  String mytext = "";
                                                                                  
                                                                                  class _peerwidgetState extends State {
                                                                                    Widget build(BuildContext context) {
                                                                                      return Scaffold(
                                                                                        appBar: AppBar(
                                                                                            title: const Text("Somecrab", textDirection: TextDirection.ltr),
                                                                                            actions: [
                                                                                              IconButton(
                                                                                                  icon: const Icon(Icons.settings),
                                                                                                  onPressed: () {
                                                                                                    print("OPENING SETTINGS FOR BACKGROUND COLOR AND SUCH");
                                                                                                  }),
                                                                                            ]),
                                                                                        body: SingleChildScrollView(
                                                                                          child: Column(children: [
                                                                                            Container(
                                                                                              child: Text(mytext),
                                                                                            ),
                                                                                            ElevatedButton(
                                                                                              style: ElevatedButton.styleFrom(
                                                                                                minimumSize: const Size(140, 50),
                                                                                              ),
                                                                                              onPressed: () {
                                                                                                print("location");
                                                                                                //setstate oderso, nächsts Bild holle
                                                                                                locationpermission();
                                                                                              },
                                                                                              child: Column(
                                                                                                // Replace with a Row for horizontal icon + text
                                                                                                children: const [
                                                                                                  Icon(Icons.arrow_forward),
                                                                                                  Text("Ask location"),
                                                                                                ],
                                                                                              ),
                                                                                            ),
                                                                                            ElevatedButton(
                                                                                              style: ElevatedButton.styleFrom(
                                                                                                minimumSize: const Size(140, 50),
                                                                                              ),
                                                                                              onPressed: () {
                                                                                                print("storage");
                                                                                                //setstate oderso, nächsts Bild holle
                                                                                                storagepermission();
                                                                                              },
                                                                                              child: Column(
                                                                                                // Replace with a Row for horizontal icon + text
                                                                                                children: const [
                                                                                                  Icon(Icons.arrow_forward),
                                                                                                  Text("Ask storage"),
                                                                                                ],
                                                                                              ),
                                                                                            ),
                                                                                            ElevatedButton(
                                                                                              style: ElevatedButton.styleFrom(
                                                                                                minimumSize: const Size(140, 50),
                                                                                              ),
                                                                                              onPressed: () {
                                                                                                print("Kill all");
                                                                                                //setstate oderso, nächsts Bild holle
                                                                                                closeall();
                                                                                              },
                                                                                              child: Column(
                                                                                                // Replace with a Row for horizontal icon + text
                                                                                                children: const [
                                                                                                  Icon(Icons.arrow_forward),
                                                                                                  Text("Kill all"),
                                                                                                ],
                                                                                              ),
                                                                                            ),
                                                                                            ElevatedButton(
                                                                                              style: ElevatedButton.styleFrom(
                                                                                                minimumSize: const Size(140, 50),
                                                                                              ),
                                                                                              onPressed: () {
                                                                                                print("CONNECT");
                                                                                                //setstate oderso, nächsts Bild holle
                                                                                  
                                                                                                setState(() {
                                                                                                  connect();
                                                                                                });
                                                                                              },
                                                                                              child: Column(
                                                                                                // Replace with a Row for horizontal icon + text
                                                                                                children: const [
                                                                                                  Icon(Icons.arrow_forward),
                                                                                                  Text("CONNECT"),
                                                                                                ],
                                                                                              ),
                                                                                            ),
                                                                                            ElevatedButton(
                                                                                              style: ElevatedButton.styleFrom(
                                                                                                minimumSize: const Size(140, 50),
                                                                                              ),
                                                                                              onPressed: () {
                                                                                                print("DISCOVER");
                                                                                                //setstate oderso, nächsts Bild holle
                                                                                                setState(() {
                                                                                                  discover();
                                                                                                });
                                                                                              },
                                                                                              child: Column(
                                                                                                // Replace with a Row for horizontal icon + text
                                                                                                children: const [
                                                                                                  Icon(Icons.arrow_forward),
                                                                                                  Text("DISCOVER"),
                                                                                                ],
                                                                                              ),
                                                                                            ),
                                                                                          ]),
                                                                                        ),
                                                                                      );
                                                                                    }
                                                                                  }
                                                                                  
                                                                                  onConnectionInitiated() {
                                                                                    mytext = "onConnectionInitiated";
                                                                                  }
                                                                                  
                                                                                  onConnectionResult() {
                                                                                    mytext = "onConnectionResult";
                                                                                  }
                                                                                  
                                                                                  onDisconnected() {
                                                                                    mytext = "onConnectionDisconnected";
                                                                                  }
                                                                                  
                                                                                  onEndpointFound() {
                                                                                    mytext = "onEndpointFound";
                                                                                  }
                                                                                  
                                                                                  onEndpointLost() {
                                                                                    mytext = "onEndpointLost";
                                                                                  }
                                                                                  
                                                                                  connect() async {
                                                                                    print("connecting started...");
                                                                                    mytext = "connection started";
                                                                                    try {
                                                                                      await Nearby().startAdvertising(
                                                                                        userName,
                                                                                        strategy,
                                                                                        onConnectionInitiated: (String id, ConnectionInfo info) {
                                                                                          print("connection initiated!" + id + info.toString());
                                                                                  
                                                                                          onConnectionInitiated();
                                                                                          // Called whenever a discoverer requests connection
                                                                                  
                                                                                          Nearby().acceptConnection(id, onPayLoadRecieved: (endpointId, payload) {
                                                                                            // called whenever a payload is recieved.
                                                                                          }, onPayloadTransferUpdate: (endpointId, payloadTransferUpdate) {
                                                                                            // gives status of a payload
                                                                                            // e.g success/failure/in_progress
                                                                                            // bytes transferred and total bytes etc
                                                                                          });
                                                                                        },
                                                                                        onConnectionResult: (String id, Status status) {
                                                                                          print("connected?");
                                                                                          onConnectionResult();
                                                                                          // Called when connection is accepted/rejected
                                                                                        },
                                                                                        onDisconnected: (String id) {
                                                                                          print("disconnected?");
                                                                                          // Callled whenever a discoverer disconnects from advertiser
                                                                                          onDisconnected();
                                                                                        },
                                                                                        serviceId: "com.simon.fluttershit", // uniquely identifies your app
                                                                                      );
                                                                                    } catch (exception) {
                                                                                      print("insufficient permissions or some error!");
                                                                                      // platform exceptions like unable to start bluetooth or insufficient permissions
                                                                                    }
                                                                                  }
                                                                                  
                                                                                  discover() async {
                                                                                    mytext = "discovery started";
                                                                                    print("Discovery started!");
                                                                                    try {
                                                                                      await Nearby().startDiscovery(
                                                                                        userName,
                                                                                        strategy,
                                                                                        onEndpointFound: (String id, String userName, String serviceId) {
                                                                                          print("found something: " + id + userName + serviceId);
                                                                                          onEndpointFound();
                                                                                  
                                                                                          // to be called by discover whenever an endpoint is found
                                                                                  // callbacks are similar to those in startAdvertising method
                                                                                          try {
                                                                                            Nearby().requestConnection(
                                                                                              userName,
                                                                                              id,
                                                                                              onConnectionInitiated: (id, info) {},
                                                                                              onConnectionResult: (id, status) {},
                                                                                              onDisconnected: (id) {},
                                                                                            );
                                                                                          } catch (exception) {
                                                                                            // called if request was invalid
                                                                                          }
                                                                                        },
                                                                                        serviceId: "com.simon.fluttershit",
                                                                                        onEndpointLost: (String? endpointId) {
                                                                                          print("was lost" + endpointId.toString());
                                                                                          onEndpointLost();
                                                                                        }, // uniquely identifies your app
                                                                                      );
                                                                                    } catch (e) {
                                                                                      print("insufficient permissions or some error!" + e.toString());
                                                                                      // platform exceptions like unable to start bluetooth or insufficient permissions
                                                                                    }
                                                                                  }
                                                                                  
                                                                                  void locationpermission() {
                                                                                    Nearby().askLocationPermission();
                                                                                  }
                                                                                  
                                                                                  void storagepermission() {
                                                                                    Nearby().askExternalStoragePermission();
                                                                                  }
                                                                                  
                                                                                  void closeall() {
                                                                                    Nearby().stopAdvertising();
                                                                                    Nearby().stopDiscovery();
                                                                                  }
                                                                                  
                                                                                  
                                                                                  
                                                                                  

                                                                                  EDIT It seems to work with my Samsung tablet and my huawei mate 10 LTE, but not with my Huawei P40 pro!

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-27 at 14:18

                                                                                  There were multiple problems here:

                                                                                  1. Not all permissions were given, as kindly pointed out by @TheFunk
                                                                                  2. Huawei P40 Pro doesn't have google services, thus not communicating properly via Peer To Peer
                                                                                  3. List item
                                                                                  4. I was using the P2P strategy STAR, instead of cluster, which now seems to work.
                                                                                  5. My focus on NFC was wrong, because it doesn't matter if the device has NFC or not.
                                                                                  6. My assumption that both devices need the same userName seems to be wrong. They can be different, as long as they're declared to find each EndPointId.

                                                                                  Note: This question is one of two, which are about the same nearby_connections library of Flutter.
                                                                                  For me this question has been solved and if you have trouble finding a working code you should check out this question, where I've posted the entire connection code, which works but does not yet receive packages. Flutter using nearby_connections in Peer to Peer to send and Receive a Package

                                                                                  Source https://stackoverflow.com/questions/70772404

                                                                                  QUESTION

                                                                                  How does the disconnect event works in socket.io?
                                                                                  Asked 2022-Jan-12 at 00:53

                                                                                  I followed a tutorial and was able to copy/build a simple real time web app. I understand everything from the code except for one thing. The 'disconnect' event. I removed most of the code for simplification, but it goes like this:

                                                                                  //server.js
                                                                                  io.on('connection', (socket) => {
                                                                                          //...I removed code from here for simplification
                                                                                          
                                                                                          socket.on('disconnect', () => {
                                                                                              socket.broadcast.emit('user-disconnected', users[socket.id]);
                                                                                              delete users[socket.id];
                                                                                          })
                                                                                  })
                                                                                  
                                                                                  //client.js
                                                                                  //...a lot of code removed from here for simplification
                                                                                  socket.on('user-disconnected', myname =>
                                                                                          {appendMessage(`${myname} left`)}
                                                                                  )
                                                                                  

                                                                                  For my surprise, this code works and when an user closes the window or leaves the page it appends the message the user left, but how does it know the user left? As far as I know, the 'disconnect' word is just a string with no other semantic meaning, right? I mean, it's not like, for example, the addEventListener('click') function which 'click' is a built-in event which means something. From my understanding, the events in socket.io are 'made-up' words by the programmer to help with server/client communication, right? Therefore, I don't understand how leaving the page triggers the 'disconnect' event here. Would someone enlighten me, please?

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-12 at 00:53

                                                                                  The disconnect event is a built-in socket.io event that tells you when a client disconnects.

                                                                                  The socket.io client JavaScript uses the beforeunload event listener on the window, which executes before the tab closes, then sends a "I'm gonna die" message to the server, then vanishes.

                                                                                  The server can also attempt to ping the client and if nothing returns, oops, disconnected.

                                                                                  On the other hand, the client can manually disconnect from the server with:

                                                                                  socket.disconnect();
                                                                                  

                                                                                  This sends a disconnect message to the server then disconnects. You can reconnect with:

                                                                                  socket.connect();
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/70675098

                                                                                  QUESTION

                                                                                  Perform action on seen/unseen messages with socket.io
                                                                                  Asked 2021-Dec-31 at 07:26

                                                                                  What is the best practice to handle seen/unseen messages in a chat room application based on Nodejs/SocketIO/React.

                                                                                  Consider User1 sends a message to a room. If another user has seen that message, notify all users that the state of message has been seen.

                                                                                  In my opinion using message brokers can be the better solution instead socket. I actually think that socket should only handle chat messages that are synchronously. but for seen/unseen status I prefer message brokers that are asynchronous. Are there any solutions or best practice in large scale applications?

                                                                                  ANSWER

                                                                                  Answered 2021-Dec-31 at 07:26

                                                                                  It's unclear what you have currently tried, meaning that I can only advise solutions in order to achieve your aim.

                                                                                  To firstly identify that a message was seen, IntersectionObserver is an inbuilt API that detects when an element has entered the viewport, meaning that it is visible, therefore; obviously seen. I have added comments in the code below where you should add a function to call to the server that the message was seen, however, that's up to you to implement.

                                                                                  const observer = new window.IntersectionObserver(([entry]) => {
                                                                                    if (entry.isIntersecting) {
                                                                                      // Send a message to the server that the user has viewed the message.
                                                                                      // Eg. socket.emit('read-message', message.id)
                                                                                      return
                                                                                    }
                                                                                  }, {
                                                                                    root: null,
                                                                                    threshold: 0.1,
                                                                                  })
                                                                                  observer.observe(document.getElementById(message.id));
                                                                                  

                                                                                  Additionally, there's no need to use message broker, as socket.io can handle simple interactions such as this.

                                                                                  You then need to send a message to the server that denotes the specified message ID was seen, then broadcast to every other client that the state was changed, and update it to read - if that's needed.

                                                                                  Source https://stackoverflow.com/questions/70539234

                                                                                  QUESTION

                                                                                  Ngfor doesn't actualize on reloading page (Angular + RXJS)
                                                                                  Asked 2021-Dec-24 at 12:07

                                                                                  Hi i'm building a chat app with angular for a school project i'm using firebase for my backend and i have an issue with my ngfor.

                                                                                  For exemple if i reload the page i will see nothing unless i hover my routerlink on my navbar. However sometime it will work after some time on the page without any action

                                                                                  When i recieve message i need to be on the page to see them ...

                                                                                  When i reload my page in first time my array is empty this may be what makes the ngfor bug array on reload.

                                                                                  I'm using ngOnInit() to subscribe :

                                                                                  messages: Message[];
                                                                                    messageSubscription: Subscription;
                                                                                  
                                                                                    constructor(private messageService: MessageService, private router: Router) { 
                                                                                      
                                                                                    }
                                                                                  
                                                                                    ngOnInit(): void {
                                                                                      this.messageSubscription = this.messageService.messageSubject.subscribe(
                                                                                        (messages: Message[]) => {
                                                                                          console.log(messages)
                                                                                          this.messages = messages;
                                                                                        }
                                                                                      );
                                                                                      this.messageService.getMessage();
                                                                                      this.messageService.emitMessage();
                                                                                    }
                                                                                  
                                                                                    ngOnDestroy(): void {
                                                                                        this.messageSubscription.unsubscribe();
                                                                                    }
                                                                                  

                                                                                  This is my html template :

                                                                                  
                                                                                      
                                                                                      
                                                                                          
                                                                                              

                                                                                  {{message.displayName}}

                                                                                  {{message.createdAt | date: 'short'}}

                                                                                  {{message.text}}

                                                                                  Here you can find my service with my getMessage() function and emitMessage():

                                                                                    messages:Message[] = [];
                                                                                    messageSubject = new Subject();
                                                                                    constructor() { }
                                                                                  
                                                                                    emitMessage(){
                                                                                      this.messageSubject.next(this.messages);
                                                                                    }
                                                                                  
                                                                                    saveMessage(newMessage: Message){
                                                                                      firebase.database().ref('/message').push(newMessage);
                                                                                    }
                                                                                  
                                                                                    getMessage(){
                                                                                      firebase.database().ref('/message')
                                                                                        .on('value', (data) => {
                                                                                          this.messages = data.val() ? Object.values(data.val()): [];
                                                                                          this.emitMessage();
                                                                                        });
                                                                                    }
                                                                                  

                                                                                  And this is the repo of my project: https://github.com/Zuxaw/AngularChatApp

                                                                                  If anyone has a solution I'm interested

                                                                                  ANSWER

                                                                                  Answered 2021-Dec-24 at 11:41

                                                                                  I think you might need to use the child_added event instead of value in your getMessage method.
                                                                                  Check if you're receiving data on time in your getMessage method, if not it's most probably, because of the event.
                                                                                  But one thing that I don't understand is why you're calling emitMessage inside getMessage and also calling it inside your component after getMessage, try to evade that.

                                                                                  Source https://stackoverflow.com/questions/70472450

                                                                                  QUESTION

                                                                                  BrokenPipeError on socket
                                                                                  Asked 2021-Nov-13 at 09:53

                                                                                  I created a messenger using Python Socket, when I use two clients, for example, when one user leaves the chat, the second user can send 1-2 more messages and after that the server stops accepting messages from other users, that is there is a well-known error Broken pipe 32. I understand the terminology of the error, perhaps the error lies on my server in a While True loop (a loop that includes all the actions that users carry out among themselves), because there is a fabulous code in the form:

                                                                                  if not data:
                                                                                      print(f'User {name1} leave')
                                                                                      break
                                                                                  

                                                                                  but I need it, because without it the server will fly away in a straight word, and if a similar mechanism is made, the server will still be able to receive information from users.

                                                                                  Hope for mutual understanding, any help would be accepted and appreciated. Server and client code is below:

                                                                                  server: 
                                                                                  
                                                                                  import socket
                                                                                  import threading
                                                                                  import time
                                                                                  
                                                                                  HOST = '127.0.0.1'
                                                                                  PORT = 8888
                                                                                  
                                                                                  server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                                                                                  server.bind((HOST, PORT))
                                                                                  
                                                                                  server.listen(15)
                                                                                  print(f'Server {HOST}:{PORT} start.')
                                                                                  
                                                                                  users = [] 
                                                                                  sort = []
                                                                                  
                                                                                  
                                                                                  def crypto(text, key):
                                                                                      encrypt = ''
                                                                                  
                                                                                      for i in text:
                                                                                          encrypt += chr(ord(i) + key)
                                                                                  
                                                                                      return encrypt   
                                                                                  
                                                                                  
                                                                                  def listen_decode(user, addr):
                                                                                      print(f'User IP-address {addr[0]} login..')
                                                                                      sort.append(user) 
                                                                                      user.send('Encode'.encode('utf-8'))
                                                                                      user.send('Name'.encode('utf-8'))
                                                                                      name1 = user.recv(1024).decode('utf-8')
                                                                                      users.append(name1)
                                                                                  
                                                                                      
                                                                                      while True:
                                                                                          data = user.recv(1024).decode('utf-8')
                                                                                          b1 = time.ctime()
                                                                                          atribute = ' | '
                                                                                          data_crypto = crypto(data, 4)
                                                                                          print(f'{name1} sent message: {data_crypto} ' + atribute + '' + b1 + ' ')
                                                                                  
                                                                                          for i in sort:
                                                                                              if(i != server and i != user):
                                                                                                  i.sendall(f'{name1} > {data}'.encode('utf-8'))
                                                                                      
                                                                                          if not data:
                                                                                              print(f'User {name1} leave')
                                                                                              break
                                                                                  
                                                                                  
                                                                                  def start_server():
                                                                                      
                                                                                      while True:
                                                                                         user_socket, addr = server.accept()
                                                                                         potok_info = threading.Thread(target=listen_decode, args=(user_socket, addr))
                                                                                         potok_info.start()
                                                                                  
                                                                                  
                                                                                  if __name__ == '__main__':
                                                                                      start_server()
                                                                                  

                                                                                  client:

                                                                                  from tkinter import messagebox
                                                                                  from tkinter import *
                                                                                  import _tkinter 
                                                                                  import socket
                                                                                  import threading
                                                                                  import os
                                                                                  
                                                                                  
                                                                                  window = Tk()
                                                                                  
                                                                                  window.title('Login')
                                                                                  window.geometry('320x200')
                                                                                  window.resizable(True, True)
                                                                                  
                                                                                  HOST = '127.0.0.1'
                                                                                  PORT = 8888
                                                                                  
                                                                                  client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                                                                                  client.connect((HOST, PORT))
                                                                                  
                                                                                  name = StringVar()
                                                                                  password = StringVar()
                                                                                  
                                                                                  def encrypt(text, key):
                                                                                      encrypt1 = ''
                                                                                  
                                                                                      for i in text:
                                                                                          encrypt1 += chr(ord(i) - key)
                                                                                  
                                                                                      return encrypt1
                                                                                  
                                                                                  def send_message():
                                                                                  
                                                                                      while True:
                                                                                          data = client.recv(1024)
                                                                                          print('\r\r' + data.decode('utf-8') + '\n' + f'you: ', end='')
                                                                                  
                                                                                  
                                                                                  def chat():
                                                                                  
                                                                                      string_name = name.get()
                                                                                  
                                                                                      if('Name' in client.recv(1024).decode('utf-8')):
                                                                                          name1 = string_name
                                                                                          client.send(name1.encode('utf-8'))
                                                                                  
                                                                                          potok = threading.Thread(target=send_message)
                                                                                          potok.start()
                                                                                  
                                                                                  
                                                                                          while True:
                                                                                              msg = input('you: ')
                                                                                              client.send(msg.encode('utf-8'))
                                                                                  
                                                                                  
                                                                                  
                                                                                  def crypt():     
                                                                                      
                                                                                      string_name = name.get()
                                                                                      string_password = password.get()
                                                                                  
                                                                                      try:
                                                                                          user_encryption_selection = (encryption_listbox.get(encryption_listbox.curselection()))
                                                                                      except _tkinter.TclError:
                                                                                          messagebox.showerror('Error', 'Enter type message')
                                                                                  
                                                                                  
                                                                                  
                                                                                      if string_name == 'John':
                                                                                          if string_password == '5555':
                                                                                              if user_encryption_selection == 'Use Encrypted':
                                                                                                  window.after(1000, lambda: window.destroy())
                                                                                  
                                                                                                  menu = Tk()
                                                                                  
                                                                                                  menu.title('Menu Chat')
                                                                                                  menu.geometry('500x350')
                                                                                                  menu.resizable(False, False)
                                                                                  
                                                                                                  menu_button = Button(menu, text='Global chat', command=chat, height=1, width=18)
                                                                                                  menu_button.grid(padx=150)
                                                                                  
                                                                                                  menu.mainloop()
                                                                                          else:
                                                                                              messagebox.showerror('Error', 'Error password')
                                                                                      else:
                                                                                          messagebox.showerror('Error', 'Error name')
                                                                                  
                                                                                      
                                                                                  entry = Entry(window, textvariable=name, width=10)
                                                                                  entry.grid(column=1, pady=7, padx=4)
                                                                                  
                                                                                  label = Label(window, text='Enter name: ')
                                                                                  label.grid(row=0, padx=1)
                                                                                  
                                                                                  entry1 = Entry(window, textvariable=password, width=10)
                                                                                  entry1.grid(column=1, pady=7, padx=2)
                                                                                  
                                                                                  label1 = Label(window, text='Enter password: ')
                                                                                  label1.grid(row=1, padx=1)
                                                                                  
                                                                                  listbox = Listbox(window, selectmode=SINGLE, width=12, height=2)
                                                                                  listbox.grid(column=1, row=2, pady=7, padx=2)
                                                                                  
                                                                                  
                                                                                  
                                                                                  encryption_options = ['Use Encrypted']
                                                                                  encryption_listbox = Listbox(window, selectmode=SINGLE, width=10, height=1)
                                                                                  encryption_listbox.grid(column=1, row=2, pady=7, padx=2)
                                                                                  for i in encryption_options:
                                                                                      encryption_listbox.insert(END, i)  
                                                                                  
                                                                                  label_crypto = Label(window, text='Type message: ', bg='black', fg='red')
                                                                                  label_crypto.grid(row=2)
                                                                                  
                                                                                  button = Button(window, text='Enter', command=crypt)
                                                                                  button.grid(pady=30)
                                                                                  
                                                                                  
                                                                                  
                                                                                  window.mainloop()
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Nov-13 at 09:53

                                                                                  perhaps the error lies on my server in a While True loop (a loop that includes all the actions that users carry out among themselves), because there is a fabulous code in the form:

                                                                                  if not data:
                                                                                      print(f'User {name1} leave')
                                                                                      break
                                                                                  

                                                                                  You already spotted the place of the error's cause. The error occurs because the server keeps trying to send to a disconnected client (in the loop immediately above that code). To stop the server trying this, you just have to remove the client from sort (the list of connected clients) at that place where you recognize the disconnection, i. e. insert sort.remove(user) before the break.

                                                                                  Source https://stackoverflow.com/questions/69935312

                                                                                  QUESTION

                                                                                  How to handle thousands of messages in a real-time group chat with Firestore?
                                                                                  Asked 2021-Nov-10 at 14:53

                                                                                  I need some help with Firestore building a chat app. I've looked at the documentation but I couldn't find the answer I need.

                                                                                  I'm building a real-time chat (many-to-many) that must handle thousands of messages, and those messages can also be edited, deleted and undeleted. The main problem is that loading all the messages once (as Firebase suggests) and then manage them on the FrontEnd side freezes my frontend application for the huge amount of messages. I tried to do that with the pagination API but I got some edge cases e.g.

                                                                                  let last = null;
                                                                                  
                                                                                  // Execute the first query saving the last doc
                                                                                  const ref = db
                                                                                   .collection('chat')
                                                                                   .orderBy('timestamp')
                                                                                   .limit(10)
                                                                                   .onSnapshot(({docs}) => {
                                                                                      last = docs[docs.length - 1]
                                                                                     // my logic
                                                                                   })
                                                                                  
                                                                                  // When needed I'll execute the second query starting from the last doc
                                                                                  // of the previous query
                                                                                  const ref = db
                                                                                   .collection('chat')
                                                                                   .orderBy('timestamp')
                                                                                   .limit(10)
                                                                                   .startAfter(last)
                                                                                   .onSnapshot(({docs}) => {
                                                                                      last = docs[docs.length - 1]
                                                                                      // my logic
                                                                                   })
                                                                                  

                                                                                  If the last document returned by the first query is deleted, I get the update only from the first query, e.g.

                                                                                  [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] // original docs from the first query
                                                                                  [10,11,12,13,14,15,16,17,18,19] // original docs from the second query
                                                                                  

                                                                                  Deleting the document 9 triggers the update from the first query so on my frontend I will have the document 10 duplicated.

                                                                                  [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10] // updated docs from the first query
                                                                                  [10,11,12,13,14,15,16,17,18,19] // original docs from the second query
                                                                                  

                                                                                  I'm guessing that there are also other edge cases that I hadn't considered. Do you have some suggestion aboutn how can I handle this big amount of messages with Firebase? Is there any error in my approach with the pagination? Or maybe this is the wrong approach?

                                                                                  ANSWER

                                                                                  Answered 2021-Nov-10 at 14:53

                                                                                  Your approach is fine, but it turns out that pagination and realtime updates with a cursor based API lead to some tricky edge-cases.

                                                                                  You'd have to either remove the duplicate documents based on their ID and then have pages with different sizes, or update the starting point of the second query (and then later queries as you have more pages).

                                                                                  There are more such edge cases, which is one of the reasons the FirestorePagingAdapter in FirebaseUI doesn't handle realtime updates.

                                                                                  Source https://stackoverflow.com/questions/69895158

                                                                                  QUESTION

                                                                                  How to get information from a client socket and display information on a server?
                                                                                  Asked 2021-Oct-25 at 20:20

                                                                                  How do I force the server to receive messages from the client and display the message: "{name} send message: {data}"? For example, a user sends a message to another user, and when a user named John sends the message "Hello Alice, how are you?", The server will be displayed at this point - John will send a message: Hello Alice, how are you? I will be grateful for your help. I hope will find the answer to this question in this article. Code below:

                                                                                  server:

                                                                                  import threading
                                                                                  import socket
                                                                                  
                                                                                  HOST = '127.0.0.1'
                                                                                  PORT = 8888
                                                                                  
                                                                                  server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                                                                                  server.bind((HOST, PORT))
                                                                                  
                                                                                  server.listen(15)
                                                                                  print(f'Server {HOST}:{PORT} start.')
                                                                                  
                                                                                  users = []
                                                                                  
                                                                                  def send_all(data):
                                                                                      for user in users:
                                                                                          user.send(data)
                                                                                  
                                                                                  def listen_user(user):
                                                                                      print('Listening user')
                                                                                      
                                                                                      while True:
                                                                                          data = user.recv(1024)
                                                                                          print(f'User sent {data}')
                                                                                  
                                                                                          send_all(data)
                                                                                  
                                                                                  def start_server():
                                                                                      while True:
                                                                                          user_socket, addr = server.accept()
                                                                                          users.append(user_socket)
                                                                                  
                                                                                          potok_info = threading.Thread(target=listen_user, args=(user_socket,))
                                                                                          potok_info.start()
                                                                                  
                                                                                  
                                                                                  if __name__ == '__main__':
                                                                                      start_server()
                                                                                  

                                                                                  client:

                                                                                  import socket
                                                                                  import time
                                                                                  import threading
                                                                                  import os
                                                                                  
                                                                                  HOST = '127.0.0.1'
                                                                                  PORT = 8888
                                                                                  
                                                                                  client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                                                                                  client.connect((HOST, PORT))
                                                                                  
                                                                                  
                                                                                  def send_message():
                                                                                      print('Enter name: ')
                                                                                      name = input()
                                                                                      while True:
                                                                                          data = client.recv(1024)
                                                                                          print(data.decode('utf-8'))
                                                                                          msg = (f'{name} send message {data}')
                                                                                          client.send(msg.encode('utf-8')) # this
                                                                                          
                                                                                          
                                                                                  def send_server():
                                                                                      
                                                                                      listen_thread = threading.Thread(target=send_message)
                                                                                      listen_thread.start()
                                                                                  
                                                                                      while True:
                                                                                          client.send(input('you: ').encode('utf-8'))
                                                                                  
                                                                                          
                                                                                  
                                                                                  if __name__ == '__main__':
                                                                                      os.system('clear')
                                                                                      print('***** Welcome in Security Chat. *****')
                                                                                      send_server()
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Oct-25 at 20:20

                                                                                  I modified your code like that.

                                                                                  This is your server script.

                                                                                  import threading
                                                                                  import socket
                                                                                  
                                                                                  HOST = '127.0.0.1'
                                                                                  PORT = 8888
                                                                                  
                                                                                  server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                                                                                  server.bind((HOST, PORT))
                                                                                  
                                                                                  server.listen(15)
                                                                                  print(f'Server {HOST}:{PORT} start.')
                                                                                  
                                                                                  users = [] # To store their name
                                                                                  sort = [] # To store their socket
                                                                                  
                                                                                  def listen_user(user):
                                                                                      print('Listening user')
                                                                                      sort.append(user)  # Store their socket in sort[]
                                                                                      user.send('Name'.encode('utf-8')) # send 'Name' to clients
                                                                                      name = user.recv(1024).decode('utf-8') # Receive their name
                                                                                      users.append(name) # Store their name in user[]
                                                                                  
                                                                                      while True:
                                                                                          data = user.recv(1024).decode('utf-8')
                                                                                          print(f'{name} sent {data}')
                                                                                  
                                                                                          for i in sort: # Send received messages to clients
                                                                                             if(i != server and i != user): # Filter server and message sender. Send message except them.
                                                                                                 i.sendall(f'{name} > {data}'.encode('utf-8'))
                                                                                     
                                                                                      user.close() # To close client socket connection.
                                                                                  
                                                                                  def start_server():
                                                                                      while True:
                                                                                         user_socket, addr = server.accept()
                                                                                         potok_info = threading.Thread(target=listen_user, args=(user_socket, ))
                                                                                         potok_info.start()
                                                                                  
                                                                                  
                                                                                  if __name__ == '__main__':
                                                                                      start_server()
                                                                                  

                                                                                  And This is your client script,

                                                                                  import socket
                                                                                  import time
                                                                                  import threading
                                                                                  import os
                                                                                  
                                                                                  HOST = '127.0.0.1'
                                                                                  PORT = 8888
                                                                                  
                                                                                  client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                                                                                  client.connect((HOST, PORT))
                                                                                  
                                                                                  def send_message():
                                                                                  
                                                                                     if('Name' in client.recv(1024).decode('utf-8')): # If 'Name' received. It allows you to send the name.
                                                                                         name  = input('Enter Name : ') # Type name
                                                                                         client.send(name.encode('utf-8'))
                                                                                  
                                                                                     while True:
                                                                                         data = input('Enter : ') # Enter message
                                                                                         client.send(data.encode('utf-8'))
                                                                                      
                                                                                         receive = client.recv(1024).decode('utf-8')# Receive messages from other clients.
                                                                                         print(receive)
                                                                                  
                                                                                  def send_server():
                                                                                  
                                                                                     listen_thread = threading.Thread(target=send_message)
                                                                                     listen_thread.start()      
                                                                                  
                                                                                  if __name__ == '__main__':
                                                                                     os.system('clear')
                                                                                     print('***** Welcome in Security Chat. *****')
                                                                                     send_server()
                                                                                  

                                                                                  Add remove some part in your code. Study it carefully then you can identify errors in your code.

                                                                                  Source https://stackoverflow.com/questions/69712309

                                                                                  QUESTION

                                                                                  all messages time stamps keep updating to current time when a message is sent
                                                                                  Asked 2021-Oct-24 at 02:28

                                                                                  below is my code in flutter, when I send a message all the timestamps for every message update to the current time, how do I ensure the times don't change on any old messages? I have pulled the timestamp out correctly just missing what I am doing wrong to save the individual time stamp. I am not using a firebase timestamp just using what dart gives me for DateTime

                                                                                  import 'dart:ffi';
                                                                                  import 'package:bardsf/components/card_data.dart';
                                                                                  import 'package:bardsf/screens/admin/admin_chat.dart';
                                                                                  
                                                                                  import 'package:bardsf/screens/main_screens/qr_screen.dart';
                                                                                  
                                                                                  import 'package:bardsf/screens/workouts/workout_selector.dart';
                                                                                  import 'package:flutter/material.dart';
                                                                                  import 'package:firebase_auth/firebase_auth.dart';
                                                                                  import 'package:cloud_firestore/cloud_firestore.dart';
                                                                                  import 'package:bardsf/components/reusable_cards.dart';
                                                                                  import 'package:font_awesome_flutter/font_awesome_flutter.dart';
                                                                                  import '../chat/chat_selector_screen.dart';
                                                                                  import 'package:bardsf/screens/chat/chat_screen.dart';
                                                                                  import 'package:intl/intl.dart';
                                                                                  
                                                                                  
                                                                                  late String messageText;
                                                                                  class HomePageScreen extends StatefulWidget {
                                                                                    static const String id = 'home_page_screen';
                                                                                  
                                                                                  
                                                                                    @override
                                                                                    _HomePageScreenState createState() => _HomePageScreenState();
                                                                                  }
                                                                                  
                                                                                  class _HomePageScreenState extends State {
                                                                                    final messageTextController = TextEditingController();
                                                                                    final _firestore = FirebaseFirestore.instance;
                                                                                  
                                                                                    final _auth = FirebaseAuth.instance;
                                                                                    late User loggedInUser;
                                                                                  
                                                                                    static const TextStyle optionStyle = TextStyle(
                                                                                        fontSize: 30, fontWeight: FontWeight.bold);
                                                                                    @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 messagesStream() async {
                                                                                      await for (var snapshot in _firestore.collection('messages').orderBy(
                                                                                          'timestamp').snapshots()) {
                                                                                        for (var message in snapshot.docs) {
                                                                                          
                                                                                          print(message.data().cast());
                                                                                        }
                                                                                      }
                                                                                    }
                                                                                  
                                                                                  
                                                                                    @override
                                                                                    Widget build(BuildContext context) {
                                                                                      return Container(
                                                                                  
                                                                                        child: Container(
                                                                                          decoration: BoxDecoration(
                                                                                              image: DecorationImage(
                                                                                                image: AssetImage("images/bar1.jpg"), fit: BoxFit.fill,
                                                                                              )
                                                                                          ),
                                                                                          child: Scaffold(
                                                                                            backgroundColor: Colors.white.withOpacity(0.5),
                                                                                  
                                                                                  
                                                                                            body: SafeArea(
                                                                                  
                                                                                  
                                                                                              child: Column(
                                                                                  
                                                                                                  crossAxisAlignment: CrossAxisAlignment.stretch,
                                                                                                  children: [
                                                                                                    ReusableCard(
                                                                                                      colour: Colors.white,
                                                                                                      cardChild: CardData(
                                                                                                        label: 'The Bar',
                                                                                                        labeltwo: 'Member Access 24/7', icon: IconData(10),
                                                                                                      ), onPress: () {},
                                                                                                    ),
                                                                                                    StreamBuilder(
                                                                                  
                                                                                                      stream: _firestore.collection('messages').snapshots(),
                                                                                                      builder: (context, snapshot) {
                                                                                                        List messageBubbles = [];
                                                                                                        if (!snapshot.hasData) {
                                                                                                          return Center(
                                                                                                            child: CircularProgressIndicator(
                                                                                                              backgroundColor: Colors.lightBlueAccent,
                                                                                                            ),
                                                                                                          );
                                                                                                        }
                                                                                                        final messages = snapshot.data!.docs;
                                                                                  
                                                                                                        for (var message in messages) {
                                                                                                          final messageText = message['text'];
                                                                                                          final messageSender = message['sender'];
                                                                                  
                                                                                                          final currentUser = loggedInUser.email;
                                                                                  
                                                                                  
                                                                                                          final messageBubble = MessageBubble(
                                                                                                            sender: 'The Bar Gym',
                                                                                                            text: messageText,
                                                                                                            isMe: currentUser == messageSender,
                                                                                                            daterTimer: DateTime.now().millisecondsSinceEpoch,
                                                                                  
                                                                                                          );
                                                                                  
                                                                                                          messageBubbles.add(messageBubble);
                                                                                                        }
                                                                                  
                                                                                  
                                                                                                        return Expanded(
                                                                                  
                                                                                                          child: Padding(
                                                                                                            padding: const EdgeInsets.all(40.0),
                                                                                                            child: Container(
                                                                                                              color: Colors.white.withOpacity(0.6),
                                                                                                              child: ListView(
                                                                                  
                                                                                                                reverse: false,
                                                                                                                padding: EdgeInsets.symmetric(
                                                                                                                    horizontal: 10, vertical: 10),
                                                                                                                children: messageBubbles,
                                                                                                              ),
                                                                                                            ),
                                                                                                          ),
                                                                                                        );
                                                                                                      },
                                                                                  
                                                                                  
                                                                                                    ),
                                                                                  
                                                                                  
                                                                                                  ]
                                                                                              ),
                                                                                            ),
                                                                                  
                                                                                          ),
                                                                                        ),
                                                                                  
                                                                                      );
                                                                                    }
                                                                                  }
                                                                                  
                                                                                  class MessageBubble extends StatelessWidget {
                                                                                  
                                                                                  
                                                                                    MessageBubble({required this.sender,required this.text,required this.isMe, required this.daterTimer });
                                                                                  
                                                                                    final String sender;
                                                                                    final String text;
                                                                                    final bool isMe;
                                                                                    final int daterTimer;
                                                                                  
                                                                                    String readTimestamp(int timestamp) {
                                                                                      var now = new DateTime.now();
                                                                                      var format = new DateFormat('M/d' ' ' 'K:m'' ''a');
                                                                                      var date = DateTime.fromMillisecondsSinceEpoch(timestamp);
                                                                                      var diff = date.difference(now);
                                                                                      var time = '';
                                                                                  
                                                                                  
                                                                                      if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
                                                                                        time = format.format(date);
                                                                                      } else {
                                                                                        if (diff.inDays == 1) {
                                                                                          time = (diff.inDays/360).toString() + 'DAY AGO';
                                                                                        } else {
                                                                                          time = (diff.inDays/360).toString() + 'DAYS AGO';
                                                                                        }
                                                                                      }
                                                                                  
                                                                                      return time;
                                                                                    }
                                                                                  
                                                                                  
                                                                                    @override
                                                                                  
                                                                                    Widget build(BuildContext context) {
                                                                                      return  Padding(
                                                                                        padding: EdgeInsets.all(10.0),
                                                                                        child: Column(
                                                                                          crossAxisAlignment: isMe ? CrossAxisAlignment.stretch : CrossAxisAlignment.start,
                                                                                          children: [
                                                                                            Row(
                                                                                              children: [
                                                                                                Expanded(
                                                                                                  child: Text(sender,
                                                                                                    style: TextStyle(
                                                                                                      fontSize: 12.0,
                                                                                                      color: Colors.red,
                                                                                                    ),
                                                                                                  ),
                                                                                                ),
                                                                                                Expanded(child: Text('${readTimestamp(daterTimer)}',
                                                                                                  style: TextStyle(color: Colors.black)
                                                                                                ),
                                                                                                ),
                                                                                              ],
                                                                                            ),
                                                                                            Material(
                                                                                              // borderRadius: isMe ? BorderRadius.only(topLeft: Radius.circular(30.0),
                                                                                              //   bottomLeft: Radius.circular(30.0),
                                                                                              //   bottomRight: Radius.circular(30.0),
                                                                                              //   topRight: Radius.circular(30.0)
                                                                                              // ) : BorderRadius.only(topRight: Radius.circular(30.0),
                                                                                              //   bottomLeft: Radius.circular(30.0),
                                                                                              //   bottomRight: Radius.circular(30.0),
                                                                                              //   topLeft: Radius.circular(30.0),
                                                                                              // ),
                                                                                  
                                                                                              elevation: 5.0,
                                                                                              color: isMe ? Colors.transparent : Colors.white,
                                                                                              child: Padding(
                                                                                                padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 10.0),
                                                                                                child: Text('$text',
                                                                                                  style: TextStyle( fontSize: 15.0,
                                                                                                    fontWeight: FontWeight.bold,
                                                                                                    color: isMe ? Colors.white : Colors.black,),
                                                                                                ),
                                                                                  
                                                                                              ),
                                                                                            ),
                                                                                  
                                                                                          ],
                                                                                        ),
                                                                                      );
                                                                                    }
                                                                                  }
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2021-Oct-24 at 02:21

                                                                                  Your error is in this line:

                                                                                  daterTimer: DateTime.now().millisecondsSinceEpoch,
                                                                                  

                                                                                  It seems you are overriding the value you are reading from Firestore. It should be something like this:

                                                                                  daterTimer: message['timestamp'];, 
                                                                                  

                                                                                  adjust it to your specific case

                                                                                  Let me know if this does not help.

                                                                                  Edit 1:

                                                                                  Basically, you are not reading the timestamp from Firestore, you are just reading the time now.

                                                                                  Try this:

                                                                                  daterTimer: (json['timestamp'] == null) ? null : (json['timestamp'] as Timestamp).toDate(),
                                                                                  

                                                                                  If it does not work, you need to show me what type is 'timestamp' field in Firestore as well as the code you are using to write to Firestore.

                                                                                  Edit 2:

                                                                                  I had a typo. Try this:

                                                                                  daterTimer: (message['timestamp'] == null) ? null : (message['timestamp'] as Timestamp).toDate(),
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/69693267

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install uni-app

                                                                                  You can install using 'npm i vue-cli-plugin-enn' or download it from GitHub, npm.

                                                                                  Support

                                                                                  For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit
                                                                                  CLONE
                                                                                • HTTPS

                                                                                  https://github.com/dcloudio/uni-app.git

                                                                                • CLI

                                                                                  gh repo clone dcloudio/uni-app

                                                                                • sshUrl

                                                                                  git@github.com:dcloudio/uni-app.git

                                                                                • Share this Page

                                                                                  share link

                                                                                  Explore Related Topics

                                                                                  Consider Popular Chat Libraries

                                                                                  uni-app

                                                                                  by dcloudio

                                                                                  taro

                                                                                  by NervJS

                                                                                  ItChat

                                                                                  by littlecodersh

                                                                                  python-telegram-bot

                                                                                  by python-telegram-bot

                                                                                  tinker

                                                                                  by Tencent

                                                                                  Try Top Libraries by dcloudio

                                                                                  mui

                                                                                  by dcloudioJavaScript

                                                                                  hello-uniapp

                                                                                  by dcloudioJavaScript

                                                                                  uni-ui

                                                                                  by dcloudioJavaScript

                                                                                  casecode

                                                                                  by dcloudioJavaScript

                                                                                  test-framework

                                                                                  by dcloudioJavaScript

                                                                                  Compare Chat Libraries with Highest Support

                                                                                  rasa

                                                                                  by RasaHQ

                                                                                  python-telegram-bot

                                                                                  by python-telegram-bot

                                                                                  zulip

                                                                                  by zulip

                                                                                  tinker

                                                                                  by Tencent

                                                                                  taro

                                                                                  by NervJS

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit