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 Keyset
s 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,
UUID uuid}
)
The Keyset
object has the following properties:
Properties | 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. | |
cipherKey | String | Optional | If passed, all communications to and from PubNub will be encrypted. | |
authKey | String | Optional | If Access Manager is enabled, all communications to and from PubNub are encrypted. | |
UUID | String | Yes | 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
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
final myKeyset = Keyset(
subscribeKey: 'subscribeKey',
publishKey: 'publishKey',
uuid: UUID('yourUniqueUUID'));
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 theusing
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:
Properties | Type | Required | Default | Description |
---|---|---|---|---|
defaultKeyset | Keyset | Yes | The default keyset to use. | |
networking | INetworkingModule | Optional | NetworkingModule | The default networking module to use. Inside this module, you can configure a custom origin and whether to use SSL. |
parser | IParserModule | Optional | ParserModule | The default parser module to use for parsing data. |
crypto | ICryptoModule | Optional | CryptoModule | The 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', uuid: UUID('myUniqueUUID')));
-
final pubnub = PubNub( defaultKeyset: Keyset(subscribeKey: 'mySubscribeKey', uuid: UUID('myUniqueUUID')), );
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 withssl
set totrue
. 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-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-Note
Anyone with the
secretKey
can grant and revoke permissions to your app. Never let yoursecretKey
be discovered, and to only exchange it / deliver it securely. Only use thesecretKey
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', uuid: UUID('myUniqueUUID')));
Now that the
pubnub
object is instantiated the client will be able to access the Access Manager functions. Thepubnub
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}');
break;
case MessageType.signal:
print('${envelope.publishedBy} sent a signal message: ${envelope.content}');
break;
case MessageType.objects:
print('object event received from ${envelope.publishedBy} with data ${envelope.payload['data']}');
break;
case MessageType.messageAction:
print('message action event ${envelope.payload['event']} received with data ${envelope.payload['data']}');
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']}');
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');
UUID
Description
These functions are used to set/get a user ID on the fly.
Methods
To set/get UUID
you can use the following method(s) in the Dart SDK:
var myKeyset =
Keyset(subscribeKey: 'subscribeKey', uuid: UUID('myUniqueUUID'));
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
uuid | String | Yes | UUID to be used as a device identifier. |
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID
, you won't be able to connect to PubNub.
final pubnub = PubNub(
defaultKeyset: Keyset(
subscribeKey: 'mySubscribeKey',
uuid: UUID('myUniqueUUID')));
// to know which uuid is set
var uuid = pubnub.keysets.defaultKeyset.uuid;
Authentication Key
Description
Setter and getter for users' authentication key.
Method(s)
var myKeyset = Keyset(
subscribeKey: 'subscribeKey',
authKey: 'myAuthkey',
uuid: UUID('myUniqueUUID'));
Parameter | Type | Required | Description |
---|---|---|---|
authKey | String | Yes | If Access Manager is utilized, client will use this authKey in all restricted requests. |
Basic Usage
final pubnub = PubNub(
defaultKeyset: Keyset(
subscribeKey: 'mySubscribeKey',
authKey: 'myAuthkey',
uuid: UUID('myUniqueUUID')));
Filter Expression
Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-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;
Parameter | Type | Required | Description |
---|---|---|---|
filterExpression | String | Yes | PSV2 feature to subscribe with a custom filter expression. |
Basic Usage
var myKeyset =
Keyset(subscribeKey: 'subscribeKey', uuid: UUID('myUniqueUUID'))
..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})
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. |