---
source_url: https://www.pubnub.com/docs/sdks/dart
title: Dart API & SDK Docs 7.1.0
updated_at: 2026-05-25T11:27:51.703Z
sdk_name: PubNub Dart SDK
sdk_version: 7.1.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Dart API & SDK Docs 7.1.0

PubNub Dart SDK, use the latest version: 7.1.0

Install:

```bash
dart pub add pubnub@7.1.0
```

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

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

## Overview

This guide helps you get up and running with PubNub in your Dart application. The Dart software development kit (SDK) provides a simple interface for integrating PubNub real-time messaging. 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, get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create an app (or use an existing one).
* Find your publish and subscribe keys in the app dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

### Install the SDK

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

###### Flutter app development

#### Create a Flutter project

If you do not have a Flutter project yet, create one:

```bash
flutter create my_pubnub_app
cd my_pubnub_app
```

To add PubNub to an existing app, use your project directory instead.

:::note Package
Add the **pubnub** package only. You do not need `pubnub_flutter` from the [Dart SDK repository](https://github.com/pubnub/dart) for this guide.
:::

#### Install the dependency

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

```yaml
dependencies:
  pubnub: 7.1.0
  flutter:
    sdk: flutter
```

Then run:

```bash
flutter pub get
```

#### Platform permissions

**Android** — add to `android/app/src/main/AndroidManifest.xml` (most `flutter create` templates include this already):

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

**iOS** — no extra configuration is required; internet access is allowed by default.

**macOS** — if App Sandbox is enabled, allow outbound network access in both `macos/Runner/DebugProfile.entitlements` and `macos/Runner/Release.entitlements`:

```xml
<key>com.apple.security.network.client</key>
<true/>
```

Without `com.apple.security.network.client`, publish and subscribe can fail with a `RequestOtherException`. Rebuild after changing entitlements (`flutter run -d macos`).

#### Pass your keys at run time (recommended)

Use [compile-time environment variables](https://docs.flutter.dev/deployment/flavors#passing--dart-define-values) instead of hardcoding keys in source:

```bash
flutter run \
  --dart-define=PUBNUB_SUBSCRIBE_KEY=sub-c-XXXXXXXX \
  --dart-define=PUBNUB_PUBLISH_KEY=pub-c-XXXXXXXX
```

Read them in Dart with `String.fromEnvironment('PUBNUB_SUBSCRIBE_KEY')` and `String.fromEnvironment('PUBNUB_PUBLISH_KEY')`. You can use `demo` for both keys to try PubNub quickly (rate-limited, public keyset).

###### Non-Flutter platforms

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

```yaml
dependencies:
  pubnub: 7.1.0
```

Then run:

```bash
dart pub get
```

#### Create a Dart project

PubNub must run inside a Dart package (with `pubspec.yaml`), not as a standalone script file:

```bash
dart create my_pubnub_app
cd my_pubnub_app
```

Add `pubnub` to `pubspec.yaml`, run `dart pub get`, then place the example code in `bin/pubnub_example.dart` and run:

```bash
dart run bin/pubnub_example.dart
```

#### Source code

Clone the [GitHub repository](https://github.com/pubnub/dart):

```bash
git clone https://github.com/pubnub/dart
```

View the [supported platforms](https://www.pubnub.com/docs/sdks/dart/platform-support) for more information about compatibility.

:::tip Fastest path
The sections below break the flow into steps. For a copy-paste-ready app, jump to the [complete example](#complete-example) and [run the app](#run-the-app).
:::

## Steps

### Initialize PubNub

#### Flutter app development

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.

```dart
// Import required packages
import 'dart:async';

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

class PubNubApp extends StatefulWidget {
  @override
  _PubNubAppState createState() => _PubNubAppState();
}

class _PubNubAppState extends State<PubNubApp> {
  // PubNub instance
  late PubNub pubnub;
  // Subscription for messages
  late Subscription subscription;
  // Channel name
  final String channel = "my_channel";
  // Messages list
  List<String> messages = [];

  @override
  void initState() {
    super.initState();
    
    // Initialize PubNub
    pubnub = PubNub(
      defaultKeyset: Keyset(
        subscribeKey: 'demo', // Replace with your subscribe key
        publishKey: 'demo',   // Replace with your publish key
        userId: UserId('flutter_user'),
      ),
    );
    
    // Setup PubNub functionality
    setupPubNub();
  }
  
  void setupPubNub() {
    // We'll add subscription code here
  }
  
  @override
  void dispose() {
    // Clean up resources (dispose returns Future<void>)
    unawaited(subscription.dispose());
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // UI implementation will go here
    return Scaffold(
      appBar: AppBar(
        title: Text('PubNub Flutter Example'),
      ),
      body: Center(
        child: Text('PubNub initialized'),
      ),
    );
  }
}
```

#### Non-Flutter platforms

In the IDE of your choice, create a new Dart file with the following content. This is the minimum configuration you need to send and receive messages with PubNub.

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

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

// Create PubNub instance with default keyset
var pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'demo', // Replace with your subscribe key
    publishKey: 'demo',   // Replace with your publish key
    userId: UserId('myUniqueUserId'),
  ),
);
```

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/dart/api-reference/configuration) section of the SDK documentation.

### Set up event listeners

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

#### Flutter app development

In your Flutter application, add this code to your `setupPubNub()` method. Store the listener so you can cancel it in `dispose()`:

```dart
StreamSubscription<Envelope>? _messageListener;

void setupPubNub() {
  // Create a subscription to the channel
  subscription = pubnub.subscribe(channels: {channel});
  
  // Set up message listener
  _messageListener = 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
  subscription.presence.listen((presence) {
    print('Presence event: ${presence.event}');
  });
}
```

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

```dart
@override
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]),
              );
            },
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _messageController,
                  decoration: InputDecoration(
                    hintText: 'Type a message',
                  ),
                ),
              ),
              IconButton(
                icon: Icon(Icons.send),
                onPressed: () {
                  sendMessage(_messageController.text);
                  _messageController.clear();
                },
              ),
            ],
          ),
        ),
      ],
    ),
  );
}
```

Don't forget to add the controller and cancel the listener in `dispose()`:

```dart
final TextEditingController _messageController = TextEditingController();

@override
void dispose() {
  _messageListener?.cancel();
  unawaited(subscription.dispose());
  _messageController.dispose();
  super.dispose();
}
```

#### Non-Flutter platforms

Add the following code to set up listeners for messages:

```dart
// Define the channel
final channel = "my_channel";

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

// Set up message listener
subscription.messages.listen((message) {
  print('Received message: ${message.content}');
});

// You can also listen for presence events
subscription.presence.listen((presence) {
  print('Presence event: ${presence.event}');
});
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/dart/api-reference/configuration#listeners) 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 JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

#### Flutter app development

Add a method to publish messages in your Flutter application:

```dart
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
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('Failed to send message: $e')),
    );
  }
}
```

#### Non-Flutter platforms

Here's how to publish messages in a Dart application:

```dart
Future<void> publishMessage() async {
  try {
    // Message to publish
    final message = {'text': 'Hello, world!', 'sender': 'dart_user'};
    
    print('Message to send: $message');
    
    // Publish the message to the channel
    final result = await pubnub.publish(channel, message);
    print('Message "${result.description}" with timetoken: ${result.timetoken}');
  } catch (e) {
    print('Error publishing message: $e');
  }
}

// Call the function
await publishMessage();
```

## Complete example

### Flutter app development

```dart
import 'dart:async';

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

const _subscribeKey = String.fromEnvironment(
  'PUBNUB_SUBSCRIBE_KEY',
  defaultValue: 'demo',
);
const _publishKey = String.fromEnvironment(
  'PUBNUB_PUBLISH_KEY',
  defaultValue: 'demo',
);

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MaterialApp(home: PubNubApp()));
}

class PubNubApp extends StatefulWidget {
  const PubNubApp({super.key});

  @override
  State<PubNubApp> createState() => _PubNubAppState();
}

class _PubNubAppState extends State<PubNubApp> {
  late PubNub pubnub;
  late Subscription subscription;
  StreamSubscription<Envelope>? _messageListener;
  final String channel = 'my_channel';
  final List<String> messages = [];
  final TextEditingController _messageController = TextEditingController();

  @override
  void initState() {
    super.initState();

    // Step 1: Initialize PubNub
    pubnub = PubNub(
      defaultKeyset: Keyset(
        subscribeKey: _subscribeKey,
        publishKey: _publishKey,
        userId: UserId('flutter_user'),
      ),
    );

    // Step 2: Subscribe and listen
    subscription = pubnub.subscribe(channels: {channel});
    _messageListener = subscription.messages.listen((message) {
      if (!mounted) return;
      setState(() {
        if (message.content is Map) {
          messages.add(
            '${message.content['sender']}: ${message.content['text']}',
          );
        } else {
          messages.add(message.content.toString());
        }
      });
    });
  }

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

    try {
      // Step 3: Publish the message
      final result = await pubnub.publish(
        channel,
        {'text': text, 'sender': 'flutter_user'},
      );
      print('Published message with timetoken: ${result.timetoken}');
      _messageController.clear();
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to send message: $e')),
      );
    }
  }

  @override
  void dispose() {
    // Step 4: Clean up (dispose returns Future<void>)
    _messageListener?.cancel();
    unawaited(subscription.dispose());
    _messageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('PubNub Flutter Example')),
      body: Column(
        children: [
          Expanded(
            child: messages.isEmpty
                ? const Center(child: Text('No messages yet'))
                : ListView.builder(
                    itemCount: messages.length,
                    itemBuilder: (context, index) =>
                        ListTile(title: Text(messages[index])),
                  ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _messageController,
                    decoration: const InputDecoration(
                      hintText: 'Type a message',
                      border: OutlineInputBorder(),
                    ),
                    onSubmitted: (_) => sendMessage(_messageController.text),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: () => sendMessage(_messageController.text),
                  child: const Text('Send'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
```

### Non-Flutter platforms

```dart
import 'package:pubnub/pubnub.dart';

Future<void> main() async {
  // Step 1: Initialize PubNub with configuration
  final pubnub = PubNub(
    defaultKeyset: Keyset(
      subscribeKey: 'demo', // Replace with your subscribe key
      publishKey: 'demo',   // Replace with your publish key
      userId: UserId('myUniqueUserId'),
    ),
  );

  // Step 2: Define the channel
  final channel = "my_channel";
  
  // Step 3: Create a subscription for the channel
  final subscription = pubnub.subscribe(channels: {channel});

  // Step 4: Set up message listener
  subscription.messages.listen((message) {
    print('Received message: ${message.content}');
  });

  // Wait for connection to establish before publishing
  await Future.delayed(Duration(seconds: 1));
  
  try {
    // Step 5: Create and publish a message
    final message = {'text': 'Hello, world!', 'sender': 'dart_user'};
    print('Message to send: $message');
    
    // Publish the message to the channel
    final result = await pubnub.publish(channel, message);
    print('Message "${result.description}" with timetoken: ${result.timetoken}');
  } catch (e) {
    print('Error publishing message: $e');
  }

  // Keep the program running to receive the published message
  await Future.delayed(Duration(seconds: 2));

  // Step 6: Clean up before exiting
  await subscription.dispose();
  print('Cleanup complete.');
}
```

### Run the app

#### Flutter app development

1. Copy the complete example into lib/main.dart (or merge it into your app).
2. From your project directory, run flutter pub get.
3. Start an emulator or connect a device, then run: 1flutter run With your own keys: 1flutter run \2 --dart-define=PUBNUB_SUBSCRIBE_KEY=sub-c-XXXXXXXX \3 --dart-define=PUBNUB_PUBLISH_KEY=pub-c-XXXXXXXX
4. Enter a message and tap Send. It should appear in the list when received through the subscription.

For a minimal runnable project in the SDK repo, see [flutter_hello_pubnub](https://github.com/pubnub/dart/tree/master/examples/flutter_hello_pubnub).

:::note Testing
`flutter test` mocks HTTP requests, so widget tests are not suitable for live PubNub checks. Use `flutter run` on a device or desktop target to verify publish and subscribe.
:::

#### Non-Flutter platforms

1. Create a Dart project and add pubnub to pubspec.yaml (see Setup).
2. Save the complete example to bin/pubnub_example.dart.
3. Run: 1dart pub get2dart run bin/pubnub_example.dart

When the application runs successfully, you should see output similar to:

```text
Message to send: {text: Hello, world!, sender: dart_user}
Received message: {text: Hello, world!, sender: dart_user}
Message "Sent" with timetoken: 16967543908123456
Cleanup complete.
```

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:

| Issue | Possible solutions |
| --- | --- |
| `RequestOtherException` on publish (macOS) | Add `com.apple.security.network.client` to macOS entitlements (see [Platform permissions](#platform-permissions)) and rebuild. |
| No connection / subscribe fails | Check internet access. Verify publish and subscribe keys. Ensure firewall or proxy is not blocking PubNub. |
| Message not received | Subscribe before publishing. Confirm channel names match. Wait briefly after subscribe before the first publish. |
| Publish returns HTTP 4xx | Verify keys, Access Manager tokens, and that publish is enabled on the keyset. |
| Build errors | Add `pubnub` to `pubspec.yaml`. Run `flutter pub get` or `dart pub get`. Check imports (`package:pubnub/pubnub.dart`). |

## Next steps

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

### Build chat

* Build a full-featured chat application with typing indicators and read receipts.
* Add typing indicators and read receipts.

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/dart/api-reference/presence) to track online/offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/dart/api-reference/storage-and-playback) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/dart/api-reference/access-manager) to secure your channels.

### Real examples

* Explore our [GitHub repository](https://github.com/pubnub/dart) for more code.
* Run the minimal [flutter_hello_pubnub](https://github.com/pubnub/dart/tree/master/examples/flutter_hello_pubnub) sample (publish/subscribe UI).
* Check out the [Flutter Simple Chat](https://github.com/pubnub/flutter-ref-app-simple-chat) sample app for a full chat experience.

### More help

* Check out the [SDK reference documentation](https://www.pubnub.com/docs/sdks/dart/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **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.
* **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: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **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.