> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/chat/chat-history/dart-flutter.md).

# Dart / Flutter

Fetch and render chat history with `fetchChatHistory`.

***

## Fetch on thread open

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

const myUserId = 'user-alice';
const peerUserId = 'user-bob';

Future<void> main() async {
  final notifier = DNotifier(
    appId: 'your-app-id',
    secret: 'your-app-secret',
    transport: 'ws',
    userId: myUserId,
    onConnected: () async {
      await notifier.fetchChatHistory(
        senderId: myUserId,
        receiverIds: [peerUserId],
      );
    },
    onMessage: (msg) {
      final body = msg.payload.toJSON();

      if (body is Map && body['messages'] is List) {
        final list = body['messages'] as List;
        print('Loaded ${list.length} history messages');
        renderHistory(list);
        return;
      }

      if (body is Map && body['type'] == 'text') {
        appendLiveMessage(msg.metadata, body);
      }
    },
  );

  await notifier.connect();
}
```

***

## Merge history with live messages

```dart
final messageMap = <String, Map<String, dynamic>>{};

void upsertMessage(Map<String, dynamic> msg) {
  final id = msg['id']?.toString() ?? '${msg['sender']}_${msg['timestamp']}';
  messageMap[id] = msg;
  renderSorted(messageMap.values.toList());
}

onMessage: (msg) {
  final body = msg.payload.toJSON();

  if (body is Map && body['messages'] is List) {
    for (final item in body['messages'] as List) {
      if (item is Map) upsertMessage(Map<String, dynamic>.from(item));
    }
    return;
  }

  if (body is Map && body['type'] == 'text') {
    upsertMessage({
      'id': msg.metadata.id,
      'sender': msg.metadata.sender,
      'text': body['text'],
      'timestamp': msg.metadata.timestamp,
    });
  }
},
```

***

## Refetch after reconnect

```dart
Future<void> onReconnect(DNotifier notifier) async {
  await notifier.connect();
  await notifier.fetchChatHistory(
    senderId: myUserId,
    receiverIds: [peerUserId],
  );
}
```

***

## Troubleshooting

| Issue                       | Check                                               |
| --------------------------- | --------------------------------------------------- |
| No history in `onMessage`   | Confirm `saveHistory: true` when messages were sent |
| Empty list                  | Thread may have no persisted messages yet           |
| `StateError: Not connected` | Call after `connect()` succeeds                     |
| Duplicate messages          | Deduplicate by `metadata.id`                        |

***

## Learn more

* [Save history flag](https://dnotifier.gitbook.io/product-docs/chat/save-history.md)
* [Delete chat messages](https://dnotifier.gitbook.io/product-docs/chat/delete-messages/dart-flutter.md)
