Featured Image
Software Development

How to Build Real-Time Chat in flutter with PubNub

Real-time messaging is a must-have feature for modern apps, and Flutter is a powerful platform for building beautiful, high-performance apps for mobile and web. 

To add real-time chat to a Flutter app, developers can use PubNub, a powerful and scalable real-time messaging platform with an easy-to-use API. 

In this article, we will explore what PubNub is, its features, and the benefits of using it for real-time chat in a Flutter app. We will also provide a step-by-step guide to integrating PubNub into a Flutter project and discuss best practices for building a high-quality real-time chat app.

What is PubNub?

PubNub is a global Data Stream Network (DSN) and a real-time messaging platform that enables developers to build scalable, reliable, and secure real-time applications. It provides APIs and tools for real-time messaging, chat, presence, and data streaming.

PubNub’s global network guarantees fast and reliable delivery of messages, boasting low latency and high throughput. It supports multiple protocols and messaging formats, including JSON, XML, and binary.

In addition, PubNub provides a range of features, such as message history, presence detection, and user authentication that make it easy to build real-time applications. These features help to ensure that messages are delivered to the right recipients, at the right time, and in the right format.

PubNub can be used in a variety of applications, such as gaming, IoT, social media, and e-commerce. Its versatility and flexibility make it a popular choice among developers who need to build real-time applications quickly and efficiently.

Features of PubNub

PubNub offers a variety of features that facilitate the creation of real-time applications. These features include:

  • Scalability: PubNub’s global network enables developers to build scalable applications that can handle millions of concurrent connections and messages.
  • Reliability: PubNub ensures the prompt and dependable delivery of messages, characterized by low latency and high throughput.
  • Security: PubNub provides end-to-end encryption, access control, and other security features that ensure the safety and privacy of data.
  • Presence Detection: PubNub’s Presence API provides real-time information about who is online and active in the app.
  • Message History: PubNub provides message history functionality that allows developers to store and retrieve messages sent through the platform.
  • Multi-Platform Support: PubNub supports multiple platforms and languages, including JavaScript, Python, Java, Swift, and Objective-C.

Why use PubNub for real-time chat in Flutter?

There are several benefits of using PubNub for real-time chat in a Flutter app, including:

  • Scalability: PubNub’s global network enables developers to build real-time chat apps that can handle millions of concurrent connections and messages, without worrying about infrastructure or scaling issues.
  • Reliability: PubNub guarantees the swift and dependable delivery of messages, with low latency and high throughput, to ensure users enjoy a seamless chat experience.
  • Easy Integration: PubNub’s easy-to-use API and SDK make it easy to integrate real-time chat functionality into a Flutter app, without requiring extensive coding or technical expertise.
  • Security: PubNub provides end-to-end encryption, access control, and other security features that ensure the safety and privacy of data, ensuring that user data is protected.
  • Multi-Platform Support: PubNub supports multiple platforms and languages, including Flutter, JavaScript, Python, Java, Swift, and Objective-C, making it easy to build cross-platform applications.

How to use PubNub to perform real-time chatting in Flutter

Now that we know what PubNub is and its benefits, let’s dive into how to integrate it into a Flutter project.

Step 1: Setting up a PubNub account

Setting up a PubNub account is the first step towards using PubNub for real-time chat in Flutter. This process is straightforward and can be completed in a few simple steps.

First, go to the PubNub website and click the “Try for Free” button on the homepage. This will take you to the sign-up page, where you can create a new account by providing your email address and password.

Once you’ve signed up, you will be redirected to the PubNub dashboard, where you can create a new app. Click on the “Create New App” button and fill in the required information, such as the app name and description.

Once you’ve created a new app, you will be given two keys: a publish key and a subscribe key. These keys are used to authenticate your app and enable communication between your app and the PubNub network. 

These keys are essential for setting up PubNub in your project, so make sure to copy them down and keep them safe.

One of the advantages of using PubNub is that it provides a free tier that includes basic support and has a monthly limit of 200 active users or 1 million transactions or function executions.

This is more than enough for most small to medium-sized chat applications. Additionally, PubNub’s network is highly scalable and can handle millions of concurrent connections, making it ideal for chat applications with large user bases.

In conclusion, setting up a PubNub account is a straightforward process that can be completed in a few simple steps. 

Once you’ve created a new app and obtained your publish and subscribe keys, you can start using PubNub to enable real-time chat in your Flutter application.

Step 2: Creating a new Flutter project

After setting up your PubNub account, you can create a new Flutter project using your preferred development environment. 

If you’re new to Flutter, you can follow the official Flutter installation guide to set up your development environment. Once you have Flutter installed, you can create a new Flutter project by running the following command in your terminal:

flutter create my_chat_app

This command will create a new Flutter project with the name my_chat_app. You can replace my_chat_app with your preferred name.

Once the project is created, you can open it in your preferred code editor and start building your chat app. You can use the PubNub Flutter SDK to add real-time chat functionality to your app.

The benefits of using Flutter for your chat app development are numerous. Flutter allows you to build cross-platform applications with a single codebase, which can save you time and resources. It also comes with a wide range of pre-built widgets that simplify the process of creating visually appealing and adaptable user interfaces.

In addition, Flutter has excellent performance, which is essential for real-time chat applications. With Flutter, you can build fast and responsive chat applications that can handle high volumes of data.

Overall, creating a new Flutter project is a straightforward process, and with the PubNub Flutter SDK, you can quickly add real-time chat functionality to your app. 

Learn How to Update Flutter Project to Version 3.0

Step 3: Adding the PubNub Flutter SDK to the project

To use PubNub in your Flutter project, you need to add the PubNub Flutter SDK to your project’s dependencies. You can do this by adding the following code to your project’s pubspec.yaml file dependencies:

pubnub: ^4.2.1

Step 4: Adding PubNub Flutter SDK to your project

After installing the PubNub Flutter SDK, you can import it into your project by adding the following code to your main.dart file:

import 'package:pubnub/pubnub.dart';

void main() {
  final pubnub = PubNub(
    defaultKeyset: Keyset(
      subscribeKey: 'your-subscribe-key',
      publishKey: 'your-publish-key',
      userId: UserId('unique-id'),
    ),
  );
  runApp(MyApp(pubnub: pubnub));
}

In this code, you need to replace ‘your-subscribe-key’ and ‘your-publish-key’ with your actual PubNub subscribe key and publish key.

Step 5: Implementing the chat interface

To create a chat interface in Flutter using PubNub, you can create a new ChatScreen widget and implement the necessary components for sending and receiving messages. 

In this widget, you can use the PubNub Flutter SDK to subscribe to the chat channel and send messages to the channel.

import 'package:flutter/material.dart';
import 'package:pubnub/pubnub.dart';

class ChatScreen extends StatefulWidget {
  final PubNub pubnub;
  final String channel;
  const ChatScreen({super.key, required this.pubnub, required this.channel});
  @override
  ChatScreenState createState() => ChatScreenState();
}

class ChatScreenState extends State<ChatScreen> {
  final TextEditingController _controller = TextEditingController();
  final List<String> _messages = [];
  @override
  void initState() {
    super.initState();
    _initPubNub();
  }

  void _initPubNub() {
    final subscription = widget.pubnub.subscribe(channels: {widget.channel});
    subscription.messages.listen((envelope) {
      setState(() {
        _messages.add(envelope.payload!.toString());
      });
    });
  }

  Future<void> _sendMessage() async {
    await widget.pubnub.publish(widget.channel, _controller.text);
    _controller.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Real-time Messaging'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (BuildContext context, int index) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 20),
                  child: Text(_messages[index]),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 32, horizontal: 8),
            child: TextField(
              controller: _controller,
              decoration: InputDecoration(
                hintText: 'Type a message',
                suffixIcon: IconButton(
                  icon: const Icon(Icons.send),
                  onPressed: _sendMessage,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

In this code, the “ChatScreen” widget takes a “PubNub” object and a channel name as parameters. It uses the “PubNub” object to subscribe to the channel and receive messages. It also uses the “PubNub” object to publish messages to the channel.

The “initState” method initialises PubNub by calling “_initPubNub”. The “_initPubNub” method subscribes to the channel and listens for new messages. When a new message is received, it adds the message to the “_messages” list and updates the state of the widget.

The “build” method returns a “Scaffold” widget with a “ListView” for displaying the messages and a “TextField” for sending messages. When the user types a message and taps the send button, the “_sendMessage” method is called, which publishes the message to the channel using the “PubNub” object.

Step 6: Using the ChatScreen widget

Now that we have implemented all the necessary methods and functions, we can finally use the ChatScreen widget to display the chat interface. 

The ChatScreen widget is a StatefulWidget that holds the state of the chat interface.

In the build method of the ChatScreen widget, we can return a Scaffold widget that contains an AppBar, a ListView to display the messages, and a TextField to allow users to send messages.

Finally, you can use the “ChatScreen” widget in your Flutter application to perform real-time chatting. To do this, navigate to the “ChatScreen” widget from another widget in your application, passing the “PubNub” object and the channel name as parameters:

Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChatScreen(
          pubnub: pubnub,
          channel: 'my-channel',
        ),
      ),
    );

In this code, “pubnub” is the “PubNub” object that you created earlier, and “‘my-channel’” is the name of the chat channel.

And that’s it! We have successfully implemented real-time chat in Flutter using PubNub.

Best practices for real-time chat in Flutter with PubNub

To ensure that your real-time chat app is of high quality and performs well, there are some best practices that you should follow when developing with PubNub and Flutter.

  • Optimize performance: Real-time chat apps require fast and reliable communication between devices. To optimize performance, use the PubNub SDK’s built-in features such as message bundling and multiplexing.
  • Manage security: Real-time chat apps can transmit sensitive information, so it’s important to implement proper security measures such as end-to-end encryption and access controls.
  • Handle error scenarios: Real-time chat apps are prone to errors such as network connectivity issues or server downtime. Make sure to handle these scenarios gracefully and provide informative error messages to users.
  • Test thoroughly: Real-time chat apps are complex and require extensive testing to ensure that they work as expected. Test your app thoroughly on different devices and network conditions.

Comparing Native Android and Flutter: App Performance Assessment

Conclusion

In conclusion, PubNub is an excellent tool for developing real-time chat applications in Flutter. Its robust features, including scalability, reliability, and ease of integration, make it a top choice for developers. With PubNub, you can quickly build and deploy real-time chat applications with minimal coding and configuration, enabling you to focus on building the chat application’s user interface and user experience.

In this article, we have explored how to use PubNub to perform real-time chatting in Flutter. We covered setting up a PubNub account, creating a new Flutter project, adding the PubNub Flutter SDK to the project, and implementing the chat interface. Additionally, we discussed some best practices for developing high-quality real-time chat apps in Flutter with PubNub, such as optimizing performance and managing security.

Now that you have learned how to use PubNub in Flutter, you can start building your real-time chat application with confidence. Remember to use the best practices we have discussed, and always test your app thoroughly before deploying it to production. With PubNub, building real-time chat applications in Flutter has never been easier, and we hope this tutorial has been helpful in getting you started.

Looking to integrate PubNub into your project? As a certified PubNub advanced tier integration partner, we’ve got you covered. Contact us for expert assistance.

 We also offer top-notch Flutter app development and software product development services. Learn more about how we can help bring your vision to life.

author
Yash Savsani