How to Build a Flutter Chat App
Tags: flutter, tutorial
Published: 2021-05-14 19:03:50

In this article, we are going to demonstrate how to create a simple peer-to-peer (p2p) chat application with the [Backendless SDK for Flutter](https://backendless.com/introducing-backendless-flutter-sdk/). This will give you an overview of the process needed to integrate your Backendless server-side with your Flutter chat app client-side.


[Flutter](https://backendless.com/developers/#flutter) is a popular hybrid frontend framework for mobile and [web app development](https://backendless.com/best-backend-for-flutter-web/). With the Backendless SDK for Flutter, Backendless is easily integrated as a powerful [Codeless backend](https://backendless.com/features/backendless-core/codeless) and [real-time database](https://backendless.com/features/backendless-core/real-time-data) for any Flutter app.

In the following guide, you will learn how to use Backendless APIs for Flutter to create a basic p2p chat app. Let’s get started.

##Setup A Flutter Chat App
First of all, we will create a new Backendless application in [Backendless Console](http://develop.backendless.com/) and call it `MessagingApp`.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvi6p3waaz5e7pdgw428.png) 

Now we need to create and set up the Flutter project. If you need help installing and running Flutter, please visit official [Flutter docs](https://flutter.dev/docs/get-started/install). Let’s create a sample Flutter project and call it `messaging_app`:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3lyubzqvvfyqk081d09.png)
 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/37u2dwjf35w3uvmt0lwj.png)

To use the plugin in Flutter project, we need to add `backendless_sdk` as a [dependency in pubspec.yaml file](https://flutter.io/platform-plugins/):
```
dependencies:
  backendless_sdk: ^0.0.2
```
After that, add the following import to Dart code:
```
import 'package:backendless_sdk/backendless_sdk.dart';
```
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/80umnsy0lo5njcdzoplz.png)
 
Don’t forget to initialize the Backendless SDK. Call `Backendless.initApp()` and pass three arguments: application ID, Android API key, and iOS API key. These values must be obtained in from your Backendless Console dashboard.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eu2l9fhtbzqlwvhbrob5.png) 

Now we are ready to use the [Backendless APIs](https://backendless.com/docs/flutter/index.html).

##[Subscription API](https://backendless.com/docs/flutter/pubsub_subscription_introduction.html)
For a messaging app, we need to [subscribe](https://backendless.com/feature/pub-sub-messaging/) to the channel:
```
void initListeners() async {
  Channel channel = await Backendless.Messaging.subscribe("myChannel");
  channel.addMessageListener(onMessageReceived);
}
```
and implement `onMessageReceived` function:
```
void onMessageReceived(PublishMessageInfo messageInfo) {
  DateTime time = DateTime.fromMillisecondsSinceEpoch(messageInfo.timestamp);
  setState(() => _messages += "${time.hour}:${time.minute}:${time.second} ${messageInfo.headers['name']}: ${messageInfo.message}\n");
}
```
Now, when we receive the message from a server we will display the date, author name and the message itself. Note: the `onMessageReceived` function can receive `PublishMessageInfo` or `String` (just a message) arguments.

Also, we need to add the `io.socket` dependency to support real-time messaging for Android clients. Open your `build.gradle` file that is located under `android/app/` and add the following lines of code:
```
dependencies {
   implementation ('io.socket:socket.io-client:1.0.0') { 
     // excluding org.json which is provided by Android 
     exclude group: 'org.json', module: 'json' 
   }
}
```
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/akw2pbu4ktd4dfo7yl26.png) 

We are now done with the Subscription API. Now let’s implement message publishing.

##[Publishing API](https://backendless.com/docs/flutter/pubsub_general_publish_api.html)
First, let’s create a user interface and add a `TextField` to display messages and an input field:
```
@override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: Text(widget.title),
     ),
     body: Stack(
       children: <Widget>[
         Align(
           alignment: Alignment.topLeft,
           child: Text("$_messages")
         ),
         Align(
           alignment: Alignment.bottomLeft,
           child: TextField(
             onSubmitted: onMessageSubmitted,
             controller: myController,
             decoration: InputDecoration(
               fillColor: Colors.black12, filled: true
             ),
           ),
         ),
       ],
     ),
   );
 }
```
```
String _messages = "";
final myController = new TextEditingController();
```
Next, implement the publishing function:
```
void onMessageSubmitted(String message) async {
  Backendless.Messaging.publish(message, channelName: "myChannel",
    publishOptions: PublishOptions()..headers = {"name":"Maksym"});
  myController.clear();
}
```
And that’s it. Run the application and say hello!

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bcwst0b6yml6p9yofp2q.png)
 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vd3gf9nqcix2dihqngzn.png)

You can find the Flutter chat app [full sample project here](https://github.com/4lfant/messaging_app). Next, you can learn about [using custom classes with the Backendless SDK for Flutter](https://backendless.com/how-to-use-custom-classes-in-flutter-sdk/).

Once you’re ready, you can learn about [implementing push notifications for Flutter in the your Backendless backend](https://backendless.com/push-notification-setup-for-flutter-sdk/).

Thanks for reading and enjoy using the Backendless platform!