Presence API for Dart SDK
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
Presence lets you track who is online or offline and store custom state information. Presence shows:
- When a user has joined or left a channel
- How many users are subscribed to a particular channel (occupancy)
- Which channels a user or device is subscribed to
- Presence state associated with these users
Learn more about our Presence feature in the Presence overview.
Here now
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
This method returns information about the current state of a channel, including a list of unique user IDs (universally unique identifiers, UUIDs) currently subscribed to the channel and the total occupancy count of the channel.
Cache
This method has a 3-second response cache time.
Method(s)
To call Here Now you can use the following methods in the Dart SDK:
1pubnub.hereNow(
2 {Keyset? keyset,
3 String? using,
4 Set<String> channels = const {},
5 Set<String> channelGroups = const {},
6 StateInfo? stateInfo,
7 int limit,
8 int offset}
9)
keyset#- Override for the PubNub default keyset configuration.
using#- Keyset name from the
keysetStoreto be used for this method call. channels#- The
channelsto get the 'here now' details of. channelGroups#- The
channelGroupsto get the 'here now' details of. Wildcards are not supported. stateInfo#- If
true, the response will include the presence states of the users forchannels/channelGroups. limit#- Maximum number of occupants to return per channel. Valid range:
0-1000. Use0to get occupancy counts without user details. offset#- Zero-based starting index for pagination. Returns occupants starting from this position in the list. Must be
>= 0. Requireslimit > 0. Use withlimitto paginate through large occupant lists.
Sample code
Get a list of UUIDs subscribed to 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 get presence information
14 String channel = 'my_channel';
15
show all 28 linesReturns
The hereNow() operation returns a HereNowResult which contains the following operations:
| Property Name | Type | Description |
|---|---|---|
totalChannels | int | Total channels. |
totalOccupancy | int | Total occupancy. |
channels | Map<String?, ChannelOccupancy> | A map with values of ChannelOccupancy for each channel. See ChannelOccupancy for more details. |
nextOffset | int? | If not all UUIDs could be returned due to the limit, this property contains the offset value to use for fetching the next page. If null, there are no more UUIDs to fetch. |
ChannelOccupancy
| Property Name | Type | Description |
|---|---|---|
channelName | String | Channel name. |
count | int | Occupancy of the channel. |
uuids | Map<String, OccupantInfo> | A map of OccupantInfo, see OccupantInfo for more details. |
OccupantInfo
| Property Name | Type | Description |
|---|---|---|
uuid | String | UUID of the user. |
state | dynamic | State of the user. |
Other examples
Returning state
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
1var result =
2 await pubnub.hereNow(channels: {'my_channel'}, stateInfo: StateInfo.all);
Example response:
1{
2 "status" : 200,
3 "message" : "OK",
4 "service" : "Presence",
5 "uuids" : [
6 {
7 "uuid" : "myUUID0"
8 },
9 {
10 "state" : {
11 "abcd" : {
12 "age" : 15
13 }
14 },
15 "uuid" : "myUUID1"
show all 38 linesReturn occupancy only
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
To return only occupancy for a channel, set the relevant flags to exclude UUIDs and state.
1var result =
2 await pubnub.hereNow(channels: {'my_channel'});
Example response:
1{
2 "status": 200,
3 "message": "OK",
4 "payload": {
5 "channels": {
6 "81d8d989-b95f-443c-a726-04fac323b331": {
7 "uuids": [ "70fc1140-uuid-4abc-85b2-ff8c17b24d59" ],
8 "occupancy": 1
9 },
10 "81b7a746-d153-49e2-ab70-3037a75cec7e": {
11 "uuids": [ "91363e7f-uuid-49cc-822c-52c2c01e5928" ],
12 "occupancy": 1
13 },
14 "c068d15e-772a-4bcd-aa27-f920b7a4eaa8": {
15 "uuids": [ "ccfac1dd-uuid-4afd-9fd9-db11aeb65395" ],
show all 23 linesHere now for channel groups
1var result = await pubnub.hereNow(channelGroups: {'cg1'});
Example response:
1{
2 occupancy : 4,
3 uuids : ['123123234t234f34fuuid', '143r34f34t34fq34quuid', '23f34d3f4rq34r34ruuid', 'w34tcw45t45tcw435uuid']
4}
Announce heartbeat
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
A device linked to the UUID in the keyset can notify channels and channelGroups about its presence.
Method(s)
To call Announce Heartbeat you can use the following methods in the Dart SDK:
1pubnub.announceHeartbeat(
2 {Keyset? keyset,
3 String? using,
4 Set<String> channels = const {},
5 Set<String> channelGroups = const {},
6 int? heartbeat}
7)
keyset#- Override for the PubNub default keyset configuration.
using#- Keyset name from the
keysetStoreto be used for this method call. channels#- The
channelsto notify. channelGroups#- The
channelGroupsto notify. heartbeat#- It is used to set the presence timeout period. It overrides the default value of 300 for Presence Timeout.
Sample code
Announce heartbeat to a single channel
1var result = await pubnub.announceHeartbeat(channels: {'my_channel'});
Announce heartbeat to a channel group
1var result = await pubnub.announceHeartbeat(channelGroups: {'cg1'});
Returns
The announceHeartbeat() operation returns a HeartbeatResult object which does not have actionable data.
Announce leave
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
A device linked to the UUID in the keyset can notify channels and channelGroups that it has left (is no longer present).
Method(s)
To call Announce Leave you can use the following methods in the Dart SDK:
1pubnub.announceLeave(
2 {Keyset? keyset,
3 String? using,
4 Set<String> channels = const {},
5 Set<String> channelGroups = const {}}
6)
Sample code
Announce leave to a single channel
1var result = await pubnub.announceLeave(channels: {'my_channel'});
Announce leave to a channel group
1var result = await pubnub.announceLeave(channelGroups: {'cg1'});
Returns
The announceLeave() operation returns a LeaveResult object which has following property.
| Property Name | Type | Description |
|---|---|---|
action | String | Action name, for example leave. |
User state
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
Clients can set a dynamic custom state (score, game state, location) for their users on one or more channels and store it on a channel as long as the user stays subscribed.
The state is not persisted, and when the client disconnects, the state data is lost. For more information, refer to Presence State.
Method(s)
Set state
To call Set State you can use the following method in the Dart SDK:
1pubnub.setState(
2 dynamic state, {
3 Keyset? keyset,
4 String? using,
5 Set<String> channels = const {},
6 Set<String> channelGroups = const {},
7})
staterequired#- The
stateas a JSON object to set for the specified channels or channel groups. keyset#- Override for the PubNub default keyset configuration.
using#- Keyset name from the
keysetStoreto be used for this method call. channels#- Set of
channelsto set thestate. channelGroups#- Set of
channelGroupsto set thestate.
Get state
To call Get State you can use the following method in the Dart SDK:
1pubnub.getState({
2 Keyset? keyset,
3 String? using,
4 Set<String> channels = const {},
5 Set<String> channelGroups = const {}
6})
Sample code
Set state
1var state = {'is_typing': true};
2
3var result = await pubnub.setState(
4 state,
5 channels: {'my_channel'}
6);
Get state
1var result = await pubnub.getState(
2 channels: {'ch1', 'ch2', 'ch3'},
3 channelGroups: {'cg1', 'cg2'}
4);
Returns
Set state
The setState operation returns a SetUserStateResult object which indicates the success of the operation.
Get state
The getState operation returns a GetUserStateResult object which contains the following operations:
stateByUUID()#- Map of
UUIDsand their associated user states.