Dart API & SDK Docs 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 or create an account 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
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
- Non-Flutter platforms
Create a Flutter project
If you do not have a Flutter project yet, create one:
1flutter create my_pubnub_app
2cd my_pubnub_app
To add PubNub to an existing app, use your project directory instead.
Package
Add the pubnub package only. You do not need pubnub_flutter from the Dart SDK repository for this guide.
Install the dependency
To integrate PubNub into your Flutter project, add this dependency to your pubspec.yaml file:
1dependencies:
2 pubnub: 7.1.0
3 flutter:
4 sdk: flutter
Then run:
1flutter pub get
Platform permissions
Android — add to android/app/src/main/AndroidManifest.xml (most flutter create templates include this already):
1<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:
1<key>com.apple.security.network.client</key>
2<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 instead of hardcoding keys in source:
1flutter run \
2 --dart-define=PUBNUB_SUBSCRIBE_KEY=sub-c-XXXXXXXX \
3 --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).
To integrate PubNub into your Dart project, add this dependency to your pubspec.yaml file:
1dependencies:
2 pubnub: 7.1.0
Then run:
1dart pub get
Create a Dart project
PubNub must run inside a Dart package (with pubspec.yaml), not as a standalone script file:
1dart create my_pubnub_app
2cd my_pubnub_app
Add pubnub to pubspec.yaml, run dart pub get, then place the example code in bin/pubnub_example.dart and run:
1dart run bin/pubnub_example.dart
Source code
Clone the GitHub repository:
1git clone https://github.com/pubnub/dart
View the supported platforms for more information about compatibility.
Fastest path
The sections below break the flow into steps. For a copy-paste-ready app, jump to the complete example and run the app.
Steps
Initialize PubNub
- Flutter app development
- Non-Flutter platforms
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.
1// Import required packages
2import 'dart:async';
3
4import 'package:flutter/material.dart';
5import 'package:pubnub/pubnub.dart';
6
7class PubNubApp extends StatefulWidget {
8
9 _PubNubAppState createState() => _PubNubAppState();
10}
11
12class _PubNubAppState extends State<PubNubApp> {
13 // PubNub instance
14 late PubNub pubnub;
15 // Subscription for messages
show all 62 linesIn 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.
1// Import required packages
2import 'package:pubnub/pubnub.dart';
3
4// Create PubNub instance with default keyset
5var pubnub = PubNub(
6 defaultKeyset: Keyset(
7 subscribeKey: 'demo', // Replace with your subscribe key
8 publishKey: 'demo', // Replace with your publish key
9 userId: UserId('myUniqueUserId'),
10 ),
11);
For more information, refer to the 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
- Non-Flutter platforms
In your Flutter application, add this code to your setupPubNub() method. Store the listener so you can cancel it in dispose():
1StreamSubscription<Envelope>? _messageListener;
2
3void setupPubNub() {
4 // Create a subscription to the channel
5 subscription = pubnub.subscribe(channels: {channel});
6
7 // Set up message listener
8 _messageListener = subscription.messages.listen((message) {
9 // Update UI with the received message
10 setState(() {
11 messages.add(message.content.toString());
12 });
13
14 print('Received message: ${message.content}');
15 });
show all 21 linesNow, let's update the build method to display messages:
1
2Widget build(BuildContext context) {
3 return Scaffold(
4 appBar: AppBar(
5 title: Text('PubNub Flutter Example'),
6 ),
7 body: Column(
8 children: [
9 Expanded(
10 child: ListView.builder(
11 itemCount: messages.length,
12 itemBuilder: (context, index) {
13 return ListTile(
14 title: Text(messages[index]),
15 );
show all 44 linesDon't forget to add the controller and cancel the listener in dispose():
1final TextEditingController _messageController = TextEditingController();
2
3
4void dispose() {
5 _messageListener?.cancel();
6 unawaited(subscription.dispose());
7 _messageController.dispose();
8 super.dispose();
9}
Add the following code to set up listeners for messages:
1// Define the channel
2final channel = "my_channel";
3
4// Create a subscription to the channel
5final subscription = pubnub.subscribe(channels: {channel});
6
7// Set up message listener
8subscription.messages.listen((message) {
9 print('Received message: ${message.content}');
10});
11
12// You can also listen for presence events
13subscription.presence.listen((presence) {
14 print('Presence event: ${presence.event}');
15});
For more information, refer to the 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
- Non-Flutter platforms
Add a method to publish messages in your Flutter application:
1Future<void> sendMessage(String text) async {
2 if (text.isEmpty) return;
3
4 try {
5 // Publish the message to the channel
6 final result = await pubnub.publish(
7 channel,
8 {'text': text, 'sender': 'flutter_user'},
9 );
10
11 print('Published message with timetoken: ${result.timetoken}');
12 } catch (e) {
13 print('Failed to publish message: $e');
14
15 // Show error to user
show all 20 linesHere's how to publish messages in a Dart application:
1Future<void> publishMessage() async {
2 try {
3 // Message to publish
4 final message = {'text': 'Hello, world!', 'sender': 'dart_user'};
5
6 print('Message to send: $message');
7
8 // Publish the message to the channel
9 final result = await pubnub.publish(channel, message);
10 print('Message "${result.description}" with timetoken: ${result.timetoken}');
11 } catch (e) {
12 print('Error publishing message: $e');
13 }
14}
15
show all 17 linesComplete example
- Flutter app development
- Non-Flutter platforms
1import 'dart:async';
2
3import 'package:flutter/material.dart';
4import 'package:pubnub/pubnub.dart';
5
6const _subscribeKey = String.fromEnvironment(
7 'PUBNUB_SUBSCRIBE_KEY',
8 defaultValue: 'demo',
9);
10const _publishKey = String.fromEnvironment(
11 'PUBNUB_PUBLISH_KEY',
12 defaultValue: 'demo',
13);
14
15void main() {
show all 133 lines1import 'package:pubnub/pubnub.dart';
2
3Future<void> main() async {
4 // Step 1: Initialize PubNub with configuration
5 final pubnub = PubNub(
6 defaultKeyset: Keyset(
7 subscribeKey: 'demo', // Replace with your subscribe key
8 publishKey: 'demo', // Replace with your publish key
9 userId: UserId('myUniqueUserId'),
10 ),
11 );
12
13 // Step 2: Define the channel
14 final channel = "my_channel";
15
show all 45 linesRun the app
- Flutter app development
- Non-Flutter platforms
-
Copy the complete example into
lib/main.dart(or merge it into your app). -
From your project directory, run
flutter pub get. -
Start an emulator or connect a device, then run:
1flutter runWith your own keys:
1flutter run \
2 --dart-define=PUBNUB_SUBSCRIBE_KEY=sub-c-XXXXXXXX \
3 --dart-define=PUBNUB_PUBLISH_KEY=pub-c-XXXXXXXX -
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.
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.
-
Create a Dart project and add
pubnubtopubspec.yaml(see Setup). -
Save the complete example to
bin/pubnub_example.dart. -
Run:
1dart pub get
2dart run bin/pubnub_example.dart
When the application runs successfully, you should see output similar to:
1Message to send: {text: Hello, world!, sender: dart_user}
2Received message: {text: Hello, world!, sender: dart_user}
3Message "Sent" with timetoken: 16967543908123456
4Cleanup 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) 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
- Advanced features
- Real examples
- More help
- Build a full-featured chat application with typing indicators and read receipts.
- Add typing indicators and read receipts.
- Try out Presence to track online/offline status.
- Implement Message Persistence to store and retrieve messages.
- Use Access Manager to secure your channels.
- Explore our GitHub repository for more code.
- Run the minimal flutter_hello_pubnub sample (publish/subscribe UI).
- Check out the Flutter Simple Chat sample app for a full chat experience.
- Check out the SDK reference documentation for detailed API information.
- Visit the support portal for additional resources.
- Ask the AI assistant (the looking glass icon at the top of the page) for help.