---
source_url: https://www.pubnub.com/docs/sdks/dart/api-reference/storage-and-playback
title: Message Persistence API for Dart SDK
updated_at: 2026-06-19T11:37:16.644Z
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


# Message Persistence API for Dart SDK

PubNub Dart SDK, use the latest version: 7.1.0

Install:

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

Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see [Message Persistence](https://www.pubnub.com/docs/general/storage).

You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.

You can retrieve the following:

* Messages
* Message reactions
* Files (using the File Sharing API)

## Batch history

:::warning Requires Message Persistence
This method requires that Message Persistence 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/).
:::

This function fetches historical messages from multiple channels. The `includeMessageActions` or `includeActions` flag also allows you to fetch message actions along with the messages.

It's possible to control how messages are returned and in what order. For example, you can:

* Search for messages starting on the newest end of the timeline.
* Search for messages from the oldest end of the timeline.
* Page through results by providing a `start` OR `end` timetoken.
* Retrieve a *slice* of the time line by providing both a `start` AND `end` timetoken.
* Retrieve a specific (maximum) number of messages using the `count` parameter.

Batch history returns up to 100 messages on a single channel, or 25 per channel on a maximum of 500 channels. Use the `start` and `end` timestamps to page through the next batch of messages.

:::tip Start & End parameter usage clarity
If you specify only the `start` parameter (without `end`), you will receive messages that are older than the `start` timetoken.
If you specify only the `end` parameter (without `start`), you will receive messages from that `end` timetoken and newer.
Specify values for both `start` and `end` parameters to retrieve messages between those timetokens (inclusive of the `end` value).
Keep in mind that you will still receive a maximum of 100 messages (or 25, for multiple channels) even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the `start` timetoken are necessary to page through the full set of results if more messages meet the timetoken values.
:::

### Method(s)

To run `fetchMessages()` you can use the following method(s) in the Dart SDK:

```dart
pubnub.batch.fetchMessages(
  Set<String> channels,
  {Keyset? keyset,
  String? using,
  int? count,
  Timetoken? start,
  Timetoken? end,
  bool? reverse,
  bool? includeMeta,
  bool includeMessageActions = false,
  bool includeMessageType = true,
  bool includeCustomMessageType,
  bool includeUUID = true}
) 
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channels | Set<String> | Yes |  | Specifies `channels` to return history messages from. |
| 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. |
| count | int | Optional |  | The paging object used for pagination. Set `count` to specify the number of historical messages to return per channel. If `includeMessageActions` is `false`, then `100` is the default (and maximum) value. Otherwise it's `25`. Set `start` to delimit the start of time slice (exclusive) to pull messages from. Set `end` to delimit the end of time slice (inclusive) to pull messages from. |
| start | Timetoken | Optional |  | `timetoken` denoting the start of the range requested (return values will be less than `start`). |
| end | Timetoken | Optional |  | `timetoken` denoting the end of the range requested (return values will be greater than or equal to `end`). |
| reverse | bool | Optional | `false` | Setting to `true` traverses the time line in reverse, starting with the oldest message first. |
| includeMeta | bool | Optional | `false` | Whether to include message metadata within response or not. |
| includeMessageActions | bool | Optional | `false` | The flag denoting to retrieve history messages with message actions. If `true`, the method is limited to one channel only. |
| includeMessageType | bool | Optional | `true` | The flag denoting to retrieve history messages with message type. |
| includeCustomMessageType | bool | Optional | `false` | Indicates whether to retrieve messages with the custom message type. For more information, refer to [Retrieving Messages](https://www.pubnub.com/docs/general/storage#retrieving-messages). |
| includeUUID | bool | Optional |  | The flag denoting to include message sender's UUID. |

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

Retrieve the last 25 messages on a channel:

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

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

  // Channels to fetch history from
  Set<String> channels = {'my_channel'};

  try {
    // Fetch the last 25 messages
    var result = await pubnub.batch.fetchMessages(channels, count: 25);

    // Print the fetched messages
    result.channels.forEach((channel, messages) {
      print('Channel: $channel');
      for (var entry in messages) {
        print('Message: ${entry.message}, Timetoken: ${entry.timetoken}');
      }
    });
  } catch (e) {
    print('Error fetching message history: $e');
  }
}
```

### Returns

The `fetchMessages()` operation returns a map of channels and a `List<BatchHistoryResultEntry>`:

| Property | Description |
| --- | --- |
| `channels`Type: `Map<String, List<BatchHistoryResultEntry>>` | Map of channels and their respective lists of `BatchHistoryResultEntry`. See [BatchHistoryResultEntry](#batchhistoryresultentry) for more details. |

#### BatchHistoryResultEntry

| Method | Description |
| --- | --- |
| `message`Type: `dynamic` | The message content. |
| `timetoken`Type: `Timetoken` | `Timetoken` of the message. Always returned by default. |
| `uuid`Type: `String` | UUID of the sender. |
| `actions`Type: `Map<String, dynamic>?` | If `includeMessageActions` was `true`, this contains message actions. Otherwise, it's `null`. |
| `messageType`Type: `MessageType` | Internal type of the message. |
| `customMessageType`Type: `String?` | Custom type of the message. `null` if empty. |
| `meta`Type: `Map<String, dynamic>` | If `includeMeta` was `true`, this contains message metadata. Otherwise, it's null. |
| `error`Type: `PubNubException?` | The exception thrown if message decryption failed for a given message. |

### Other examples

#### Paging history Responses

```dart
  var messages = <BatchHistoryResultEntry>[];
  var channel = 'my_channel';
  var loopResult, start, count;
  do {
    loopResult =
        await pubnub.batch.fetchMessages({channel}, start: start, count: count);

    messages.addAll((loopResult as BatchHistoryResult).channels[channel]!);

    if ((loopResult).more != null) {
      var more = loopResult.more as MoreHistory;
      start = Timetoken(BigInt.parse(more.start));
      count = more.count;
    }
  } while (loopResult.more != null);
```

## Delete messages from history

:::warning Requires Message Persistence
This method requires that Message Persistence 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/).
:::

Removes the messages from the history of a specific channel.

:::note Required setting
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable `Delete-From-History` checkbox in the key settings for your key in the Admin Portal.
Requires Initialization with secret key.
:::

### Method(s)

To `deleteMessages()` you can use the following method(s) in the Dart SDK.

```dart
pubnub.delete() 
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: `List<String>` | Specifies `channels` to delete messages from. |
| `start`Type: `Long` | Timetoken delimiting the `start` of time slice (inclusive) to delete messages from. |
| `end`Type: `Long` | Timetoken delimiting the `end` of time slice (exclusive) to delete messages from. |

### Sample code

```dart
await pubnub
  .channel('channel-name')
  .messages(
    from: Timetoken(BigInt.parse('123345')),
    to: Timetoken(BigInt.parse('123538293')),
  )
  .delete();
```

### Other examples

#### Delete specific message from history

To delete a specific message, pass the `publish timetoken` (received from a successful publish) in the `End` parameter and timetoken `+/- 1` in the `Start` parameter. For example, if `15526611838554310` is the publish timetoken, pass `15526611838554309` in Start and `15526611838554310` in End parameters respectively as shown in the following code snippet.

```dart
await pubnub
  .channel('channel-name')
  .messages(
    from: Timetoken(BigInt.parse('15526611838554309')),
    to: Timetoken(BigInt.parse('15526611838554310')),
  )
  .delete();
```

## Message counts

:::warning Requires Message Persistence
This method requires that Message Persistence 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/).
:::

Returns the number of messages published on one or more channels since a given time. The `count` returned is the number of messages in history with a `timetoken` value `greater than or equal to` than the passed value in the `channelsTimetoken`parameter.

:::note Unlimited message retention
For keys with unlimited message retention enabled, this method considers only messages published in the last 7 days.
:::

### Method(s)

To run `messageCounts()` you can use the following method(s) in the Dart SDK:

```dart
pubnub.batch.countMessages(
  dynamic channels,
  {Keyset? keyset, 
  String? using, 
  Timetoken? timetoken}
)
```

| Parameter | Description |
| --- | --- |
| `channels` *Type: `Map<String, Timetoken>` or `Set<String>` | Specifies `channels` set. Or Map of channel names and timetoken for message count. |
| `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. |
| `timetoken`Type: `Timetoken` | `timetoken` is required when channels is a `Set` of channel names. |

### Sample code

```dart
var result = await pubnub.batch.countMessages({'my_channel'},
    timetoken: Timetoken(BigInt.from(13406746780720711)));
```

### Returns

This operation returns a `CountMessagesResult` which contains the following property:

| Property Name | Type | Description |
| --- | --- | --- |
| `channels` | `Map<String, int>` | Channel names with message count. |

## History (deprecated)

:::note Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

This function fetches historical messages of a channel.

It's possible to control how messages are returned and in what order, for example you can:

* Search for messages starting on the newest end of the timeline (default behavior - `reverse` = `false`)
* Search for messages from the oldest end of the timeline by setting `reverse` to `true`.
* Page through results by providing a `start` OR `end` [timetoken](https://www.pubnub.com/docs/sdks/dart/api-reference/misc#time).
* Retrieve a *slice* of the time line by providing both a `start` AND `end` timetoken.
* Limit the number of messages to a specific quantity using the `count` parameter.

:::tip Start & End parameter usage clarity
If only the `start` parameter is specified (without `end`), you will receive messages that are **older** than and up to that `start` timetoken value. If only the `end` parameter is specified (without `start`) you will receive messages that match that `end` timetoken value and **newer**. Specifying values for both `start` *and* `end` parameters will return messages between those timetoken values (inclusive on the `end` value). Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the `start` timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
:::

#### Method(s)

To run `history()` you can use the following method(s) in the Dart SDK:

```dart
pubnub.channel(String).history(
  {ChannelHistoryOrder order = ChannelHistoryOrder.descending,
  int chunkSize = 100}
)

// OR

pubnub.channel(String).messages()
```

| Parameter | Description |
| --- | --- |
| `order` *Type: `ChannelHistoryOrder`Default: `ChannelHistoryOrder.descending` | Order of messages based on timetoken. Refer to [Channel History Order](#channel-history-order) for more details. |
| `chunkSize`Type: `int`Default: `false` | Number of returned messages. |

#### Channel history order

| Parameter | Description |
| --- | --- |
| `ascending`Type: const `ChannelHistoryOrder` | Ascending order of messages, based on timetokens. |
| `descending`Type: const `ChannelHistoryOrder` | Descending order of messages, based on timetokens. |
| `values`Type: const `List<ChannelHistoryOrder>` | A constant list of the values in this enum, in order of their declaration. |

#### Sample code

Retrieve the last 100 messages on a channel:

```dart
var history = pubnub.channel('my_channel').history(chunkSize: 100);
```

#### Returns

The `history()` operation returns a `PaginatedChannelHistory` which contains the following properties:

| Property | Description |
| --- | --- |
| `chunkSize`Type: `int` | Maximum number of fetched messages when calling `more()`. |
| `endTimetoken`Type: `Timetoken` | Upper boundary of fetched messages timetokens. |
| `hasMore`Type: `bool` | Returns true if there are more messages to be fetched. Keep in mind, that before the first `more` call, it will always be `true`. |
| `messages`Type: `List<BaseMessage>` | Readonly list of messages. It will be empty before first `more` call. Refer to the method description below for more details on the `more` call. |
| `order`Type: `ChannelHistoryOrder` | Order of messages based on timetoken. Refer to [Channel History Order](#channel-history-order) for more details. |
| `startTimetoken`Type: `Long` | Lower boundary of fetched messages timetokens. |

`PaginatedChannelHistory` has the following methods:

| Method | Returns | Description |
| --- | --- | --- |
| `more` | `Future<FetchHistoryResult>` | Fetches more messages and stores them in the `messages` property of `PaginatedChannelHistory`. |
| `reset` | `void` | Resets the history to the beginning. |

#### Base message

| Parameter | Description |
| --- | --- |
| `content`Type: `dynamic` | The message content. |
| `message`Type: `dynamic` | Alias for `content`. |
| `originalMessage`Type: `dynamic` | Original JSON message received from the server. |
| `publishedAt`Type: `Timetoken` | Timetoken at which the server accepted the message. |
| `timetoken`Type: `Timetoken` | Alias for `timetoken`. |

#### Other examples

##### Use history() to retrieve the three oldest messages by retrieving from the time line in reverse

```dart
var history = pubnub
    .channel('my_channel')
    .history(order: ChannelHistoryOrder.ascending, chunkSize: 3)
```

###### Response

```json
{
    "messages":[
        {
            "Timetoken": 0,
            "message": "Pub1"
        },
        {
            "Timetoken": 0,
            "message": "Pub2"
        },
        {
            "Timetoken": 0,
            "message": "Pub3"
        }
    ],
    "startTimeToken": 13406746729185766,
    "endTimeToken": 13406746780720711
}
```

##### History paging example

```dart
var history = pubnub.channel('asdf').history(chunkSize: 100, order: ChannelHistoryOrder.descending);
// To fetch next page:
await history.more();
// To access messages:
print(history.messages);
```

## Terms in this document

* **Message** - A unit of data transmitted between clients or between a client and a server in PubNub, containing information such as text, binary data, or structured data formats like JSON. Messages are sent over channels and can be tracked for delivery and read status.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.