Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the instant messaging function of Android Flutter based on WebSocket

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to achieve instant messaging based on WebSocket in Android Flutter". In daily operation, I believe many people have doubts about how to achieve instant messaging in Android Flutter based on WebSocket. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to achieve instant messaging in Android Flutter based on WebSocket". Next, please follow the editor to study!

Contact interface construction

Before we chat, we need to select the corresponding contact for a single chat, so we need to build a contact list. Here we use simple ListView.builder+Mock data to build the contact list. The interface is shown below, and the key is to route the id of the contact when you click on the contact, so that the receiving user is designated by the user id when sending the message.

Return ListTile (leading: _ getRoundImage (contactors [index] .avatar, 50), title: Text (contactors [index] .nickname), subtitle: Text (contactors [fontSize] .description, style: TextStyle (color: Colors.grey),), onTap: () {debugPrint (contactors.id); RouterManager.router.navigateTo (context,'${RouterManager.chatPath}? toUserId=$ {contactors [index] .id}');},) Implementation of chat Interface

We put the sent message on the right and the received message on the left, left or right through Container's margin. As for the distinction, it is distinguished by the fromUserId of the message object. If the fromUserId is consistent with the current user id, it is the sent message, otherwise it is the received message. Here, because we do not have a user system, we will first write the current user id to death. In order to chat between simulators, one of our simulators is set to user1 and the other to user2. The interface also uses ListView.builder (universal no?) Build.

Return ListView.builder (itemBuilder: (context, index) {MessageEntity message = messages [index]; double margin = 20; double marginLeft = message.fromUserId = = 'user1'? 60: margin; double marginRight = message.fromUserId = =' user1'? Margin: 60; return Container (margin: EdgeInsets.fromLTRB (marginLeft, margin, marginRight, margin), padding: EdgeInsets.all (15), alignment: message.fromUserId = 'user1'? Alignment.centerRight: Alignment.centerLeft, decoration: BoxDecoration (color: message.fromUserId = = 'user1'? Colors.green: Colors.blue, borderRadius: BorderRadius.circular (10), child: Text (message.content, style: TextStyle (color: Colors.white),);}, itemCount: messages.length,)

One of the features of the chat interface is that it will receive the latest messages pushed by StreamProvider. In order to unify, we will send and receive messages through the StreamProvider push update interface.

/ / add the message to the flow controller void sendMessage (String event, T message) {_ socket.emit (event, message); _ socketResponse.sink.add (message);} / / also add the message to the flow controller when sending the message (recvEvent, (data) {_ socketResponse.sink.add (data);})

In this way, whether receiving messages or sending messages, the chat interface will be rebuilt through StreamProvider. So the question is, how to refresh the chat list data?

MultiProvider of message interface

The message interface needs to receive the message flow of StreamProvider, and we also need to use message list data, here we use MultiProvider. The message sending box and the chat interface share ChatMessageModel (for demonstration only, it can actually be separated).

Final chatMessageModel = ChatMessageModel () / /... body: Stack (alignment: Alignment.bottomCenter, children: [MultiProvider (providers: [StreamProvider (create: (context) = > streamSocket.getResponse, initialData: null), ChangeNotifierProvider.value (value: chatMessageModel)], child: StreamDemo ()) ChangeNotifierProvider.value (child: MessageReplyBar (messageSendHandler: (message) {Map json = {'fromUserId':' user1', 'toUserId': widget.toUserId,' contentType': 'text',' content': message}) StreamSocket.sendMessage ('chat', json);}), value: chatMessageModel,),] / /.

Where ChatMessageModel is the message list status data, there is only an array of message objects and a method to add messages, and a content property is used for the message reply box.

There is a problem here. When StreamProvider pushed the message from StreamSocket, ChatMessageModel didn't know it. If you want to know, one way is to reference the ChatMessageModel object in StreamSocket and then call its addMessage method to add the message. But this increases the coupling of the two classes. Another way is trickery, that is, the build method of StreamdDemo can get the latest messages pushed by StreamSocket, which can be added to the message list after reading the latest messages here. Since we both sent and received messages earlier, we added messages to the message flow, so the processing is unified.

It should be noted that Provider does not allow you to call a method similar to notifyListeners in the component's build method to notify the component to refresh, so you cannot use notifyListeners in the ChatMessageModel's addMessage method to notify the component to refresh, otherwise the same component refresh conflict will occur. In fact, because another Provider has notified the component that it has refreshed, there is no need to notify it again. Of course, this is just a trick, and assuming that the addMessage method also needs to notify other components to refresh, this form is not desirable.

Class ChatMessageModel with ChangeNotifier {List _ messages = []; List get messages = > _ messages; String content =''; void addMessage (Map json) {_ messages.add (MessageEntity.fromJson (json));}}

Let's not consider this situation here. The build of StreamDemo deals with this part as follows. Here, there is no need to use the watch method for bar ChatMessageModel. It completely depends on the stream push of StreamProvider to update the component. Each time a message is sent or received, the message list data is updated at build time before returning to the component tree, thus ensuring that the data is up-to-date. In fact, it is equivalent to our opportunistic implementation of data exchange between the two Provider.

@ overrideWidget build (BuildContext context) {Map? MessageJson = context.watch (); if (messageJson! = null) {context.read () .addMessage (messageJson);} List messages = context.read () .messages; / / ListView part} running effect

Let's take a look at the running effect. The advantage of the simulator is that it can turn on multiple debugging. The effect is achieved, but the actual live chat is much more complicated than this, and generally do not use Socket, but if the internal App to achieve instant messaging after the application is opened, WebSocket is a good choice. The source code has been submitted, and the backend and Flutter codes are distributed as follows:

Flutter Provider partial Code (null safety version)

Back-end code (Express version)

At this point, the study on "how to achieve instant messaging in Android Flutter based on WebSocket" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report