Configuration API for PubNub Dart SDK

Dart complete API reference for building Realtime Applications on PubNub, including basic usage and sample code.

Configuration

Description

Dart SDK allows you to create various configurations for different subscribe keys. Each configuration is stored in a Keyset object.

You can use a KeysetStore to store your Keysets but make sure that individual Keyset names are unique and note that only one can be the default.

Method(s)

Keyset(
{String subscribeKey,
String publishKey,
String secretKey,
String authKey,
CipherKey cipherKey,
UserId userId}
)

The Keyset object has the following properties:

PropertiesTypeRequiredDefaultDescription
subscribeKeyStringYessubscribeKey from the Admin Portal.
publishKeyStringOptionalpublishKey from the Admin Portal (only required if publishing).
secretKeyStringOptionalsecretKey used for administrative tasks.
cipherKeyStringOptionalIf passed, all communications to and from PubNub will be encrypted.
authKeyStringOptionalIf Access Manager is enabled, all communications to and from PubNub are encrypted.
userIdStringYesuserId 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 64 alphanumeric characters.

If you don't set the userId, you won't be able to connect to PubNub.
UUIDStringYesThis 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.

Basic Usage

Required userId

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.

final myKeyset = Keyset(
subscribeKey: 'subscribeKey',
publishKey: 'publishKey',
userId: UserId('yourUniqueUserId'));

Initialization

Add PubNub to your project using one of the procedures defined in Getting Started.

Description

To use the Dart SDK, instantiate the PubNub class with a default Keyset. The default Keyset is used any time a specific Keyset isn't explicitly passed into a method. All methods that you call try to obtain the keyset according to these rules:

  • The keyset parameter has the highest priority.
  • If keyset is null, the method tries to get a keyset from the using parameter.
  • If using is null, the method tries to get the default keyset.
  • If the default keyset isn't defined, the method throws an error.

Methods

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

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

The PubNub constructor takes the following arguments:

PropertiesTypeRequiredDefaultDescription
defaultKeysetKeysetYesThe default keyset to use.
networkingINetworkingModuleOptionalNetworkingModuleThe default networking module to use. Inside this module, you can configure a custom origin and whether to use SSL.
parserIParserModuleOptionalParserModuleThe default parser module to use for parsing data.
cryptoICryptoModuleOptionalCryptoModuleThe default crypto module for data encryption and decryption.

Basic Usage

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

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

Initialization for a Read-Only client

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:

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.

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

Initializing with Access Manager

Requires Access Manager add-on

This method requires that the Access Manager add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

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:

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

Listeners

The following listeners are available:

  • message
  • signal
  • objects
  • messageAction
  • file
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
show all 55 lines

userID

Description

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:

var myKeyset =
Keyset(subscribeKey: 'subscribeKey', userId: UserId('myUniqueUserId'));
ParameterTypeRequiredDefaultDescription
userIdStringYesUser ID to be used as a device identifier.

Basic Usage

Required userId

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.

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

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

Authentication Key

Description

Setter and getter for users' authentication key.

Method(s)

var myKeyset = Keyset(
subscribeKey: 'subscribeKey',
authKey: 'myAuthkey',
userId: UserId('myUniqueUserId'));
ParameterTypeRequiredDescription
authKeyStringYesIf Access Manager is utilized, client will use this authKey in all restricted requests.

Basic Usage

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

Filter Expression

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Description

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/get filters you can use the following method. To learn more about filtering, refer to the Publish Messages documentation.

Method(s)

// to know which filter expression is set
var filterExpression = pubnub.keysets.defaultKeyset.filterExpression;
ParameterTypeRequiredDescription
filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression.

Basic Usage

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.

You can configure automatic reconnection as follows:

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})
ArgumentTypeDescription
maximumDelayintMaximum amount of milliseconds to wait until retry is executed.
backoffintBackoff amount in milliseconds.
maxRetriesintNumber of max retries.
Last updated on