Dart API & SDK Docs 5.2.0

In this guide, we'll create a simple "Hello, World" application that demonstrates the core concepts of PubNub

PubNub

PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including:

:

  • Setting up a connection
  • Sending messages
  • Receiving messages in real-time

Overview

This guide will help you get up and running with PubNub in your Dart application. Since Dart is commonly used across different platforms, we provide two implementation paths:

  • Flutter app development: For developers building mobile or web applications with Flutter
  • Non-Flutter platforms: For developers using Dart in other environments (server-side, CLI, etc.)

The core PubNub concepts and API usage remain the same across both paths, but implementation details like lifecycle management and UI updates differ. Select the appropriate tab in each section to see platform-specific guidance.

Prerequisites

Before we dive in, make sure you have:

  • A basic understanding of Dart
  • Flutter SDK or Dart SDK installed
  • Your preferred IDE (VS Code, Android Studio, etc.)
  • A PubNub account (we'll help you set this up!)

Setup

Get your PubNub keys

First things first – you'll need your PubNub keys to get started. Here's how to get them:

  • Sign in or create an account on the PubNub Admin Portal.
  • Create a new app (or use an existing one).
  • Find your publish

    Publish Key

    A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
    and subscribe

    Subscribe Key

    A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.
    keys in the app's dashboard.

When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better security and management.

Install the SDK

SDK version

Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.

To integrate PubNub into your Flutter project, add this dependency to your pubspec.yaml file:

dependencies:
pubnub: 5.2.0
flutter:
sdk: flutter

Then run:

flutter pub get

Don't forget to add internet permission:

For Android, add to your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

For iOS, no additional steps are needed as internet access is permitted by default.

View the supported platforms for more information about compatibility.

Steps

Initialize PubNub

In your Flutter project, add the PubNub initialization code to your main application file. This is the minimum configuration you need to send and receive messages with PubNub in your Flutter application.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

// Import required packages
import 'package:flutter/material.dart';
import 'package:pubnub/pubnub.dart';

class PubNubApp extends StatefulWidget {

_PubNubAppState createState() => _PubNubAppState();
}

class _PubNubAppState extends State<PubNubApp> {
// PubNub instance
late PubNub pubnub;
// Subscription for messages
late Subscription subscription;
// Channel name
show all 60 lines

For more information, refer to the Configuration section of the SDK documentation.

Set up event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

In your Flutter application, add this code to your setupPubNub() method:

void setupPubNub() {
// Create a subscription to the channel
subscription = pubnub.subscribe(channels: {channel});

// Set up message listener
subscription.messages.listen((message) {
// Update UI with the received message
setState(() {
messages.add(message.content.toString());
});

print('Received message: ${message.content}');
});

// You can also listen for presence events
show all 19 lines

Now, let's update the build method to display messages:


Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('PubNub Flutter Example'),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(messages[index]),
);
show all 44 lines

Don't forget to add the controller:

final TextEditingController _messageController = TextEditingController();

For more information, refer to the Publish and Subscribe section of the SDK documentation.

Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

Add a method to publish messages in your Flutter application:

Future<void> sendMessage(String text) async {
if (text.isEmpty) return;

try {
// Publish the message to the channel
final result = await pubnub.publish(
channel,
{'text': text, 'sender': 'flutter_user'},
);

print('Published message with timetoken: ${result.timetoken}');
} catch (e) {
print('Failed to publish message: $e');

// Show error to user
show all 20 lines

Run the app

To test your Flutter application:

  1. Launch your emulator or connect your physical device.
  2. Run your app with flutter run.
  3. You should see the PubNub Flutter example UI appear.
  4. Enter a message in the text field and tap the send button.
  5. You should see your message appear in the list as it's received back through the subscription.

Complete example

Here's the complete working example that puts everything together.

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

void main() {
runApp(MaterialApp(home: PubNubApp()));
}

class PubNubApp extends StatefulWidget {

_PubNubAppState createState() => _PubNubAppState();
}

class _PubNubAppState extends State<PubNubApp> {
// PubNub instance
late PubNub pubnub;
show all 138 lines

Run the app

To run your Flutter application:

  1. Save the code to a file (e.g., main.dart).
  2. Make sure you have a Flutter project set up.
  3. Run the app with flutter run.
  4. Enter messages and see them appear in the list.

Congratulations! You've just subscribed to a channel and sent your first message with PubNub.

Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

IssuePossible Solutions
No connection message
  • Check your internet connection.
  • Verify your publish and subscribe keys are correct.
  • Make sure you're not behind a firewall blocking PubNub's connections.
Message not received
  • Double-check that you're subscribed to the correct channel.
  • Verify that the message was actually sent (check for any error messages).
  • Make sure you're waiting long enough for the message to be delivered.
Build errors
  • Ensure you've added the PubNub dependency correctly in your pubspec.yaml.
  • Run dart pub get or flutter pub get to update dependencies.
  • Make sure all imports are correct.

For more detailed troubleshooting information, refer to the Troubleshooting section of the SDK documentation.

Next steps

Great job! 🎉 You've successfully created your first PubNub application with Dart. Here are some exciting things you can explore next:

  • Build a full-featured chat application with user presence and typing indicators.
  • Implement user Presence to show who's online.
  • Add typing indicators and read receipts.
Last updated on