---
source_url: https://www.pubnub.com/docs/sdks/dart/api-reference/configuration
title: Configuration API for Dart SDK
updated_at: 2026-06-04T11:11:35.731Z
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


# Configuration API for Dart SDK

PubNub Dart SDK, use the latest version: 7.1.0

Install:

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

Dart complete API reference for building real-time applications on PubNub, including basic usage and sample code.

## Configuration

Create configurations for different subscribe keys using a `Keyset` object.

Use `KeysetStore` to store your `Keyset`s. Ensure names are unique; only one keyset can be the default.

### Method(s)

```dart
Keyset(
  {String subscribeKey,
  String publishKey,
  String secretKey,
  String authKey,
  UserId userId}
) 
```

The `Keyset` object has the following properties:

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| subscribeKey | String | Yes |  | `subscribeKey` from the Admin Portal. |
| publishKey | String | Optional |  | `publishKey` from the Admin Portal (only required if publishing). |
| secretKey | String | Optional |  | `secretKey` used for administrative tasks. |
| authKey | String | Optional |  | If [Access Manager](https://www.pubnub.com/docs/sdks/dart/api-reference/access-manager) is enabled, the client includes this key with restricted requests. |
| userId | String | Yes |  | `userId` to use. You should set a unique identifier for the user or the device that connects to PubNub. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you don't set the `userId`, you won't be able to connect to PubNub. |
| cipherKey | String | Optional |  | This way of setting this parameter is deprecated, pass it to `crypto` instead. If passed, all communications to and from PubNub will be encrypted. |
| UUID | String | Yes |  | This parameter is deprecated, use `userId` instead. UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub. If you don't set the UUID, you won't be able to connect to PubNub. |

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

:::note Required User ID
Always set the `userId` to uniquely identify the user or device that connects to PubNub. This `userId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `userId`, you won't be able to connect to PubNub.
:::

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

void main() {
  // Configure the Keyset with required parameters
  final myKeyset = Keyset(
    subscribeKey: 'demo', 
    publishKey: 'demo', 
    userId: UserId('myUniqueUserId')
  );

  print('Keyset configured with subscribeKey: ${myKeyset.subscribeKey}');
}
```

## Initialization

Add the SDK to your project using one of the procedures in [Getting Started](https://www.pubnub.com/docs/sdks/dart).

### Description

Instantiate `PubNub` with a default `Keyset`. The default keyset is used when a method is called without an explicit keyset. Keyset resolution rules:

* If provided, the `keyset` parameter is used.
* Otherwise, the method uses the `using` parameter.
* Otherwise, the method uses the default keyset.
* If no default keyset is defined, the method throws an error.

### Methods

To initialize PubNub, you can use the following constructor in the Dart SDK:

```dart
PubNub(
  {Keyset defaultKeyset, 
  INetworkingModule networking,
  IParserModule parser, 
  ICryptoModule crypto}
) 
```

The `PubNub` constructor takes the following arguments:

| Parameter | Description |
| --- | --- |
| `defaultKeyset` *Type: `Keyset`Default: n/a | The default keyset to use. |
| `networking`Type: `INetworkingModule`Default: `NetworkingModule` | The default networking module. Configure a custom origin, SSL, and the retry policy for subscribe operations. Default retry policy: `RetryPolicy.exponential` (subscribe only). `RetryPolicy` is the type of policy to be used. Available values: RetryPolicy.none(), RetryPolicy.linear({backoff, maxRetries, maximumDelay}), RetryPolicy.exponential({maxRetries, maximumDelay}) For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle). |
| `parser`Type: `IParserModule`Default: `ParserModule` | The default parser module to use for parsing data. |
| `crypto`Type: `ICryptoModule`Default: `CryptoModule` | The cryptography module used for encryption and decryption of messages and files. Takes the `cipherKey` parameter as argument. For more information, refer to the [cryptoModule](#cryptomodule) section. |

#### cryptoModule

`cryptoModule` encrypts and decrypts messages and files. From 4.2.4 onward, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128-bit encryption and recommended 256-bit AES-CBC. For background, see [Message Encryption](https://www.pubnub.com/docs/general/setup/data-security#message-encryption) and [File Encryption](https://www.pubnub.com/docs/general/setup/data-security#file-encryption).

If you do not explicitly set the `cryptoModule` in your app and have the `cipherKey` param set in PubNub config, the client defaults to using the legacy encryption.

For detailed encryption configuration, utility methods for encrypting/decrypting files, and practical examples, see the dedicated [Encryption](https://www.pubnub.com/docs/sdks/dart/api-reference/encryption) page.

:::note Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
:::

### Sample code

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

void main() async {
  // Initialize PubNub with the configured Keyset
  final myKeyset = Keyset(
    subscribeKey: 'demo', 
    publishKey: 'demo', 
    userId: UserId('myUniqueUserId')
  );
  
  final pubnub = PubNub(defaultKeyset: myKeyset);

}
```

### Returns

Initialization returns the PubNub instance for invoking PubNub APIs like `publish()`, `subscribe()`, etc.

### Other examples

#### Initialize a non-secure client

```dart
final pubnub =
  PubNub(
    defaultKeyset: myKeyset, 
    networking: NetworkingModule(ssl: false));
```

#### Initialization for a Read-Only client

```dart
final pubnub = PubNub(
  defaultKeyset:
    Keyset(subscribeKey: 'mysubscribeKey',
    userId: UserId('myUniqueUserId')));
```

#### Initialization with custom origin

If your use-case requires to route traffic through custom domain instead of the default one, you can set up your SDK such that all your traffic is routed through `example.com`:

```dart
final pubnub = PubNub(
  defaultKeyset: myKeyset,
  networking: NetworkingModule(origin: 'example.com', ssl: true),
);
```

#### Initializing with SSL enabled

This example demonstrates how to enable PubNub Transport Layer Encryption with `SSL`. Just initialize the client with `ssl` set to `true`. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

```dart
final pubnub =
  PubNub(
    defaultKeyset: myKeyset,
    networking: NetworkingModule(ssl: true));
```

#### Initializing with Access Manager

:::note Requires Access Manager add-on
This method requires that the *Access Manager* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

:::note Secure your secretKey
Anyone with the `secretKey` can grant and revoke permissions to your app. Never let your `secretKey` be discovered, and to only exchange it / deliver it securely. Only use the `secretKey` on secure server-side platforms.
When you init with `secretKey`, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.
:::

For applications that will administer Access Manager permissions, the API is initialized with the `secretKey` as in the following example:

```dart
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'mySubscribeKey',
    secretKey: 'my_secretkey',
    userId: UserId('myUniqueUserId')));
```

Now that the `pubnub` object is instantiated the client will be able to access the Access Manager functions. The `pubnub` object will use the secretKey to sign all Access Manager messages to the PubNub Network.

## Event listeners

You can be notified of connectivity status, message, and presence notifications via the listeners. For the listeners to work, you must have a `Subscription`. For more information, refer to the [Subscription](https://www.pubnub.com/docs/sdks/dart/api-reference/publish-and-subscribe#subscription) section.

### Listeners

The following listeners are available:

* `message`
* `signal`
* `objects`
* `messageAction`
* `file`

```dart
subscription.messages.listen((envelope) {
    switch (envelope.messageType) {
      case MessageType.normal:
          print('${envelope.publishedBy} sent a message: ${envelope.content}');
          print('${envelope.channel}'); //to display the channel that message was sent on
          print('${envelope.publishedAt}'); // to display timetoken of the message received
          print('${envelope.content}'); // to display content of the message
          print('${envelope.uuid}'); // to display the uuid of the sender
          break;
      case MessageType.signal:
          print('${envelope.publishedBy} sent a signal message: ${envelope.content}');
          print('${envelope.channel}'); //to display the channel that message was sent on
          print('${envelope.publishedAt}'); // to display timetoken of the message received
          print('${envelope.content}'); // to display content of the message
          print('${envelope.uuid}'); // to display the uuid of the sender
        break;
      case MessageType.objects:
          print('object event received from ${envelope.publishedBy} with data ${envelope.payload['data']}');
          print('${envelope.channel}'); //to display the channel that message was sent on
          print('${envelope.publishedAt}'); // to display timetoken of the message received
          print('${envelope.content}'); // to display content of the message
          print('${envelope.uuid}'); // to display the uuid of the sender
        break;
      case MessageType.messageAction:
          print('message action event ${envelope.payload['event']} received with data ${envelope.payload['data']}');
          print('${envelope.channel}'); //to display the channel that message was sent on
          print('${envelope.publishedAt}'); // to display timetoken of the message received
          print('${envelope.content}'); // to display content of the message
          print('${envelope.uuid}'); // to display the uuid of the sender
        break;
      case MessageType.file:
          var fileInfo = envelope.payload['file'];
          var id = fileInfo['id']; // unique file id
          var name = fileInfo['name']; // file name
          print('${envelope.publishedBy} sends file $name with message  ${envelope.payload['message']}');
          print('${envelope.channel}'); //to display the channel that message was sent on
          print('${envelope.publishedAt}'); // to display timetoken of the message received
          print('${envelope.content}'); // to display content of the message
          print('${envelope.uuid}'); // to display the uuid of the sender
        break;
      default:
        print('${envelope.publishedBy} sent a message: ${envelope.content}');
    }
  });

  subscription.presence.listen((event) {
      print('''Presence Event with action: ${event.action},
      received from uuid: ${event.uuid}
      with time token: ${event.timetoken},
      Total Occupancy now is: ${event.occupancy}
      ''');
  });

var envelope =
    await subscription.messages.firstWhere((envelope) => envelope.channel == 'my_channel');
```

## userID

These functions are used to set/get a user ID on the fly.

### Methods

To set/get `userId` you can use the following method(s) in the Dart SDK:

```dart
var myKeyset =
  Keyset(subscribeKey: 'subscribeKey', userId: UserId('myUniqueUserId'));
```

| Parameter | Description |
| --- | --- |
| `userId` *Type: `String`Default: n/a | User ID to be used as a device identifier. |

### Sample code

:::note Required User ID
Always set the `userId` to uniquely identify the user or device that connects to PubNub. This `userId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `userId`, you won't be able to connect to PubNub.
:::

```dart
final pubnub = PubNub(
    defaultKeyset: Keyset(
        subscribeKey: 'mySubscribeKey',
        userId: UserId('myUniqueUserId')));

// to know which userId is set
var userId = pubnub.keysets.defaultKeyset.userId;
```

## Authentication key

Setter and getter for users' authentication key.

### Method(s)

```dart
var myKeyset = Keyset(
  subscribeKey: 'subscribeKey',
  authKey: 'myAuthkey',
  userId: UserId('myUniqueUserId'));
```

| Parameter | Description |
| --- | --- |
| `authKey` *Type: `String` | If Access Manager is utilized, client will use this `authKey` in all restricted requests. |

### Sample code

```dart
final pubnub = PubNub(
  defaultKeyset: Keyset(
    subscribeKey: 'mySubscribeKey',
    authKey: 'myAuthkey',
    userId: UserId('myUniqueUserId')));
```

## Filter expression

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it's applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set or get message filters, you can use the following method. To learn more about filtering, refer to the [Publish Messages](https://www.pubnub.com/docs/general/messages/publish) documentation.

### Method(s)

```dart
// to know which filter expression is set
var filterExpression = pubnub.keysets.defaultKeyset.filterExpression;
```

| Parameter | Description |
| --- | --- |
| `filterExpression` *Type: `String` | PSV2 feature to `subscribe` with a custom filter expression. |

### Sample code

```dart
var myKeyset =
    Keyset(subscribeKey: 'subscribeKey', userId: UserId('myUniqueUserId'))
    ..filterExpression = 'such=wow';

final pubnub = PubNub(defaultKeyset: myKeyset);
```

## Handling disconnects

The client may disconnect due to unpredictable network conditions. By default, the client reconnects exponentially for subscribe connections only.

For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle).

### Retry policy

You can configure how subscribe operations retry using a retry policy on the `NetworkingModule`. Non-subscribe requests never retry regardless of policy. Set the policy when constructing `PubNub` as changing it later won't re-register the networking strategy.

:::note Default retry policy
If you don't provide a policy, the SDK uses exponential retry for subscribe operations.
:::

Retries are attempted on network-related diagnostics such as host down, host lookup failed, timeouts, and unknown HTTP exceptions. The `maxRetries` cap applies to all except timeouts. Use `RetryPolicy.none()` to disable all retries (including subscribe).

You can configure automatic reconnection as follows:

```dart
var pubnub = PubNub(
    networking:
        NetworkingModule(retryPolicy: RetryPolicy.exponential(maxRetries: 10)));
```

Available retry policies include:

* `RetryPolicy.exponential({int? maxRetries, int? maximumDelay});`
* `RetryPolicy.linear({int? backoff, int? maxRetries, int? maximumDelay})`

| Argument | Type | Description |
| --- | --- | --- |
| `maximumDelay` | `int` | Maximum amount of milliseconds to wait until retry is executed. |
| `backoff` | `int` | Backoff amount in milliseconds. |
| `maxRetries` | `int` | Number of max retries. |

#### Examples

Exponential with custom limits:

```dart
final pubnub = PubNub(
  defaultKeyset: myKeyset,
  networking: NetworkingModule(
    retryPolicy: RetryPolicy.exponential(
      maxRetries: 5,
      maximumDelay: 120000, // 120s cap
    ),
  ),
);
```

Linear backoff with cap:

```dart
final pubnub = PubNub(
  defaultKeyset: myKeyset,
  networking: NetworkingModule(
    retryPolicy: RetryPolicy.linear(
      backoff: 200,          // ms per try (plus jitter)
      maxRetries: 8,
      maximumDelay: 5000,    // ms cap
    ),
  ),
);
```

Disable retries entirely:

```dart
final pubnub = PubNub(
  defaultKeyset: myKeyset,
  networking: NetworkingModule(
    retryPolicy: RetryPolicy.none(),
  ),
);
```

## Terms in this document

* **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.