How to Create a Realtime Chat App With Flutter and Node.js | by Teun Grondman | Apr, 2022

On this weblog, we are going to see make a real-time chat app utilizing Node.js because the backend and Flutter because the frontend. We are going to use sockets to speak between gadgets.

Node.js (Server-Facet)

Let’s create a brand new undertaking named chat_server and op it within the Terminal. Now run this command to start out the undertaking:

contact index.js && npm init && npm set up ws && npm set up specific

It will utterly set up the undertaking for you. When that has been accomplished open the undertaking in your favorite IDE and open up your index.js file.

That is our fundamental Websocket server that doesn’t actually do a lot now. Let’s change that now.

It will utterly run your messages! So now that that is carried out we are able to now begin with our Flutter chat app.

Flutter (Shopper-Facet)

We’ve accomplished our backend now so we are able to begin with chat app in Flutter. Run this command to start out our new Flutter undertaking:

flutter create chat_app && cd chat_app && flutter run

Open this undertaking in your IDE and open up your pubspec.yaml file and we are going to add web_socket_channel be sure that it appears to be like like this:

sdk: flutter
cupertino_icons: ^1.0.2
web_socket_channel: ^2.1.0 # Add this.
sqflite: ^2.0.2 # And this.

To begin our undertaking delete all the things in lib/primary.dart and ensure to insert this:

Now let’s additionally create a brand new file known as messages.dart the place we shall be storing messages. As a result of we shall be storing our messages domestically we are going to create a operate first for that.

That’s loads of code huh? Nicely, what this operate is doing is retrieving each message in our database. Then it checks if the message has been despatched by you or obtained.

If that has been carried out then lastly we are going to show the message. Now we are going to create one other operate in messages.dart that may ship a message to our server and insert a brand new message into our database.

This operate will retailer the message that we’ll be sending. Now that that is carried out we are going to now create a web page to show these messages.

We are going to name this web page chat_page.dart and it’ll appear like this primary.

Now to obtain messages we need to create a operate for that. We are going to name our operate getMessage() this can hyperlink ourselves to the server and pay attention for any messages. And if there’s a message we are going to show that additionally.

And that’s all there may be now you absolutely created a chat app. Now run the app with two native gadgets to see if it really works. If it doesn’t work please let me know and I’ll aid you. Thanks for studying.

More Posts