Publish/Subscribe API for Dart SDK
PubNub delivers messages worldwide in less than 30 ms. Send a message to one recipient or broadcast to thousands of subscribers.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
publish() sends a message to all channel subscribers. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel.
- Prerequisites and limitations
- Security
- Message data
- Size
- Publish rate
- Custom message type
- Best practices
- You must initialize PubNub with the publishKey.
- You don't have to be subscribed to a channel to publish to it.
- You cannot publish to multiple channels simultaneously.
Secure messages with Transport Layer Security (TLS) or Secure Sockets Layer (SSL) by setting ssl to true during initialization. You can also encrypt messages.
The message can contain any JavaScript Object Notation (JSON)-serializable data (objects, arrays, integers, strings). Avoid special classes or functions. Strings can include any UTF‑8 characters.
Don't JSON serialize
You should not JSON serialize the message and meta parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB. This includes the escaped character count and the channel name. Aim for under 1,800 bytes for optimal performance.
If your message exceeds the limit, you'll receive a Message Too Large error. To learn more or calculate payload size, see Message size limits.
You can publish as fast as bandwidth allows. There is a soft throughput limit because messages may drop if subscribers can't keep up.
For example, publishing 200 messages at once may cause the first 100 to drop if a subscriber hasn't received any yet. The in-memory queue stores only 100 messages.
 You can optionally provide the customMessageType parameter to add your business-specific label or category to the message, for example text, action, or poll. 
- Publish to a channel serially (not concurrently).
- Verify a success return code (for example, [1,"Sent","136074940..."]).
- Publish the next message only after a success return code.
- On failure ([0,"blah","<timetoken>"]), retry.
- Keep the in-memory queue under 100 messages to avoid drops.
- Throttle bursts to meet latency needs (for example, no more than 5 messages per second).
Method(s)
To Publish a message you can use the following method(s) in the Dart SDK:
1pubnub.publish(
2  String channel,
3  dynamic message,
4  {Keyset? keyset,
5  String? using,
6  dynamic meta,
7  bool? storeMessage,
8  int? ttl,
9  String? customMessageType}
10) 
| Parameter | Description | 
|---|---|
| channel*Type:  StringDefault: n/a | Destination of the message(channel ID). | 
| message*Type:  AnyDefault: n/a | The payload. | 
| keysetType:  KeysetDefault: n/a | Override for the PubNub default keyset configuration. | 
| usingType:  StringDefault: n/a | Keyset name from the keysetStoreto be used for this method call. | 
| metaType:  dynamicDefault: Not set | Metadata object which can be used with the filtering ability. | 
| storeMessageType:  boolDefault: Account default | Store message in history. If not specified, the decision depends on whether Message Persistence has been enabled for the key or not. | 
| ttlType:  intDefault: n/a | Set a per message time to live in Message Persistence. 1. If storeMessage = true, andttl = 0, the message is stored with no expiry time.2. If storeMessage = trueandttl = X(Xis an Integer value), the message is stored with an expiry time ofXhours unless you have message retention set toUnlimitedon your keyset configuration in the Admin Portal.3. If storeMessage = false, thettlparameter is ignored.4. If ttlisn't specified, then expiration of the message defaults back to the expiry value for the key. | 
| customMessageTypeType:  StringDefault: n/a | A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes -and underscores_are allowed. The value cannot start with special characters or the stringpn_orpn-.Examples: text,action,poll. | 
Sample code
Reference code
Publish a message to a channel:
1import 'package:pubnub/pubnub.dart';
2
3void main() async {
4  // Create PubNub instance with default keyset.
5  var pubnub = PubNub(
6    defaultKeyset: Keyset(
7      subscribeKey: 'demo',
8      publishKey: 'demo',
9      userId: UserId('myUniqueUserId'),
10    ),
11  );
12
13  // Channel to publish the message to
14  String channel = 'myChannel';
15
Returns
The publish() operation returns a PublishResult which contains the following operations:
| Method | Description | 
|---|---|
| descriptionType:  String | The description, for example Sent. | 
| timetokenType:  int | Returns an intrepresentation of the timetoken when the message was published. | 
Other examples
Publish with metadata
1var result = await pubnub.publish('my_channel', 'hello', meta: '<json data>', customMessageType: 'text-message');
Publishing JsonObject (Google GSON)
1var message = {'hello': 'world'};
2var result = await pubnub.publish('my_channel', message, customMessageType: 'text-message');
Publishing JsonArray (Google GSON)
1var message = ['hello', 'world'];
2var result = await pubnub.publish('my_channel', message, customMessageType: 'text-message');