---
source_url: https://www.pubnub.com/docs/sdks/dart/api-reference/presence
title: Presence API for Dart SDK
updated_at: 2026-06-26T11:05:37.638Z
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


# Presence API for Dart SDK

PubNub Dart SDK, use the latest version: 7.1.0

Install:

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

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

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](https://www.pubnub.com/docs/general/presence/overview).

## Here now

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

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.

:::note 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:

```dart
pubnub.hereNow(
  {Keyset? keyset,
  String? using,
  Set<String> channels = const {},
  Set<String> channelGroups = const {},
  StateInfo? stateInfo,
  int limit,
  int offset}
) 
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| keyset | Keyset | Optional |  | Override for the PubNub default keyset configuration. |
| using | String | Optional |  | Keyset name from the `keysetStore` to be used for this method call. |
| channels | Set<String> | Optional |  | The `channels` to get the 'here now' details of. |
| channelGroups | Set<String> | Optional |  | The `channelGroups` to get the 'here now' details of. Wildcards are not supported. |
| stateInfo | StateInfo | Optional | `false` | If `true`, the response will include the presence states of the users for `channels`/`channelGroups`. |
| limit | int | Optional | `1000` | Maximum number of occupants to return per channel. Valid range: `0-1000`. Use `0` to get occupancy counts without user details. |
| offset | int | Optional | `0` | Zero-based starting index for pagination. Returns occupants starting from this position in the list. Must be `>= 0`. Requires `limit > 0`. Use with `limit` to paginate through large occupant lists. |

### 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.
:::

#### Get a list of UUIDs subscribed to channel

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

void main() async {
  // Create PubNub instance with default keyset.
  var pubnub = PubNub(
    defaultKeyset: Keyset(
      subscribeKey: 'demo',
      publishKey: 'demo',
      userId: UserId('myUniqueUserId'),
    ),
  );

  // Channel to get presence information
  String channel = 'my_channel';

  try {
    // Get presence information
    var result = await pubnub.hereNow(channels: {channel});

    // Print the total occupancy and UUIDs
    print('Total Occupancy: ${result.totalOccupancy}');
    result.channels[channel]?.uuids.forEach((uuid, info) {
      print('UUID: $uuid, State: ${info.state}');
    });
  } catch (e) {
    print('Error retrieving presence information: $e');
  }
}
```

### Returns

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](#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](#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

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

```dart
var result =
    await pubnub.hereNow(channels: {'my_channel'}, stateInfo: StateInfo.all);
```

Example response:

```json
{
    "status" : 200,
    "message" : "OK",
    "service" : "Presence",
    "uuids" : [
        {
            "uuid" : "myUUID0"
        },
        {
            "state" : {
                "abcd" : {
                    "age" : 15
                }
            },
            "uuid" : "myUUID1"
        },
        {
            "uuid" : "b9eb408c-bcec-uuid-b4c4-fabec057ad0d"
        },
        {
            "state" : {
                "abcd" : {
                    "age" : 15
                }
            },
            "uuid" : "myUUID2"
        },
        {
            "state" : {
                "abcd" : {
                    "age" : 24
                }
            },
            "uuid" : "myUUID9"
        }
    ],
    "occupancy" : 5
}
```

#### Return occupancy only

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

To return only `occupancy` for a channel, set the relevant flags to exclude UUIDs and state.

```dart
var result =
    await pubnub.hereNow(channels: {'my_channel'});
```

Example response:

```json
{
    "status": 200,
    "message": "OK",
    "payload": {
        "channels": {
            "81d8d989-b95f-443c-a726-04fac323b331": {
                "uuids": [ "70fc1140-uuid-4abc-85b2-ff8c17b24d59" ],
                "occupancy": 1
            },
            "81b7a746-d153-49e2-ab70-3037a75cec7e": {
                "uuids": [ "91363e7f-uuid-49cc-822c-52c2c01e5928" ],
                "occupancy": 1
            },
            "c068d15e-772a-4bcd-aa27-f920b7a4eaa8": {
                "uuids": [ "ccfac1dd-uuid-4afd-9fd9-db11aeb65395" ],
                "occupancy": 1
            }
        },
        "total_channels": 3,
        "total_occupancy": 3
    },
    "service": "Presence"
}
```

#### Here now for channel groups

```dart
var result = await pubnub.hereNow(channelGroups: {'cg1'});
```

Example response:

```json
{
    occupancy : 4,
    uuids : ['123123234t234f34fuuid', '143r34f34t34fq34quuid', '23f34d3f4rq34r34ruuid', 'w34tcw45t45tcw435uuid']
}
```

## Announce heartbeat

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

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:

```dart
pubnub.announceHeartbeat(
  {Keyset? keyset,
  String? using,
  Set<String> channels = const {},
  Set<String> channelGroups = const {},
  int? heartbeat}
) 
```

| Parameter | Description |
| --- | --- |
| `keyset`Type: `Keyset`Default: n/a | Override for the PubNub default keyset configuration. |
| `using`Type: `String`Default: n/a | Keyset name from the `keysetStore` to be used for this method call. |
| `channels`Type: `Set<String>`Default: n/a | The `channels` to notify. |
| `channelGroups`Type: `Set<String>`Default: n/a | The `channelGroups` to notify. |
| `heartbeat`Type: `int`Default: n/a | 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

```dart
var result = await pubnub.announceHeartbeat(channels: {'my_channel'});
```

#### Announce heartbeat to a channel group

```dart
var result = await pubnub.announceHeartbeat(channelGroups: {'cg1'});
```

### Returns

The `announceHeartbeat()` operation returns a `HeartbeatResult` object which does not have actionable data.

## Announce leave

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

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:

```dart
pubnub.announceLeave(
  {Keyset? keyset,
  String? using,
  Set<String> channels = const {},
  Set<String> channelGroups = const {}}
) 
```

| Parameter | Description |
| --- | --- |
| `keyset`Type: `Keyset` | Override for the PubNub default keyset configuration. |
| `using`Type: `String` | Keyset name from the `keysetStore` to be used for this method call. |
| `channels`Type: `Set<String>` | The `channels` to notify. |
| `channelGroups`Type: `Set<String>` | The `channelGroups` to notify. |

### Sample code

#### Announce leave to a single channel

```dart
var result = await pubnub.announceLeave(channels: {'my_channel'});
```

#### Announce leave to a channel group

```dart
var 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

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

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](https://www.pubnub.com/docs/general/presence/presence-state).

### Method(s)

#### Set state

To call `Set State` you can use the following method in the Dart SDK:

```dart
pubnub.setState(
  dynamic state, {
  Keyset? keyset,
  String? using,
  Set<String> channels = const {},
  Set<String> channelGroups = const {},
})
```

| Parameter | Description |
| --- | --- |
| `state` *Type: `dynamic`Default: n/a | The `state` as a JSON object to set for the specified channels or channel groups. |
| `keyset`Type: `Keyset`Default: n/a | Override for the PubNub default keyset configuration. |
| `using`Type: `String`Default: n/a | Keyset name from the `keysetStore` to be used for this method call. |
| `channels`Type: `Set<String>`Default: `{}` | Set of `channels` to set the `state`. |
| `channelGroups`Type: `Set<String>`Default: `{}` | Set of `channelGroups` to set the `state`. |

#### Get state

To call `Get State` you can use the following method in the Dart SDK:

```dart
pubnub.getState({
  Keyset? keyset,
  String? using,
  Set<String> channels = const {},
  Set<String> channelGroups = const {}
})
```

| Parameter | Description |
| --- | --- |
| `keyset`Type: `Keyset`Default: n/a | Override for the PubNub default keyset configuration. |
| `using`Type: `String`Default: n/a | Keyset name from the `keysetStore` to be used for this method call. |
| `channels`Type: `Set<String>`Default: `{}` | Set of `channels` to fetch the `state`. |
| `channelGroups`Type: `Set<String>`Default: `{}` | Set of `channelGroups` to fetch the `state`. |

### Sample code

#### Set state

```dart
var state = {'is_typing': true};

var result = await pubnub.setState(
  state,
  channels: {'my_channel'}
);
```

#### Get state

```dart
var result = await pubnub.getState(
  channels: {'ch1', 'ch2', 'ch3'},
  channelGroups: {'cg1', 'cg2'}
);
```

### 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:

| Method | Description |
| --- | --- |
| `stateByUUID()`Type: `Map<String, Object>` | Map of `UUIDs` and their associated user states. |