> 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/example-minimal-chat/dart-flutter.md). Agents can also search and read this documentation through its [MCP server](https://dnotifier.gitbook.io/product-docs/~gitbook/mcp).

# Dart / Flutter

Full walkthrough: two-user 1:1 chat with history, send, and receive.

***

## Bob — receiver (Process 1)

Save as `bin/bob.dart`:

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

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

final messages = <Map<String, dynamic>>[];

Future<void> main() async {
  final notifier = DNotifier(
    appId: 'your-app-id',
    secret: 'your-app-secret',
    transport: 'ws',
    userId: myUserId,
    onConnected: () async {
      print('Bob online');
      await notifier.fetchChatHistory(
        senderId: myUserId,
        receiverIds: [peerUserId],
      );
    },
    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) messages.add(Map<String, dynamic>.from(item));
        }
        print('[history] ${(body['messages'] as List).length} messages loaded');
        for (final m in messages) {
          printMessage(m);
        }
        return;
      }

      if (body is Map && body['type'] == 'text') {
        final entry = {
          'sender': msg.metadata.sender,
          'text': body['text'],
          'timestamp': msg.metadata.timestamp,
        };
        messages.add(entry);
        printMessage(entry);
      }
    },
    onDisconnected: ({code, reason}) => print('Bob offline: $reason'),
  );

  await notifier.connect();
}

void printMessage(Map<String, dynamic> m) {
  print('  ${m['sender']}: ${m['text']}');
}
```

Run: `dart run bin/bob.dart`

***

## Alice — sender with stdin (Process 2)

Save as `bin/alice.dart`:

```dart
import 'dart:io';
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 {
      print('Alice online — type a message and press Enter');
      await notifier.fetchChatHistory(
        senderId: myUserId,
        receiverIds: [peerUserId],
      );
    },
    onMessage: (msg) {
      final body = msg.payload.toJSON();
      if (body is Map && body['messages'] is List) {
        print('[history] ${(body['messages'] as List).length} messages');
        return;
      }
      if (body is Map && body['type'] == 'text') {
        print('← ${msg.metadata.sender}: ${body['text']}');
      }
    },
    onDisconnected: ({code, reason}) => print('Alice offline: $reason'),
  );

  await notifier.connect();

  while (true) {
    stdout.write('> ');
    final line = stdin.readLineSync();
    if (line == null) break;
    final text = line.trim();
    if (text.isEmpty) continue;

    try {
      await notifier.send(
        senderId: myUserId,
        receiverId: peerUserId,
        data: {'type': 'text', 'text': text},
      );
      print('→ you: $text');
    } catch (e) {
      print('Send failed: $e');
    }
  }
}
```

Run: `dart run bin/alice.dart`

***

## Flutter minimal screen

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

class MinimalChatScreen extends StatefulWidget {
  const MinimalChatScreen({super.key, required this.notifier, required this.peerId});
  final DNotifier notifier;
  final String peerId;

  @override
  State<MinimalChatScreen> createState() => _MinimalChatScreenState();
}

class _MinimalChatScreenState extends State<MinimalChatScreen> {
  final _messages = <String>[];
  final _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    widget.notifier.fetchChatHistory(
      senderId: widget.notifier.userId,
      receiverIds: [widget.peerId],
    );
  }

  Future<void> _send() async {
    final text = _controller.text.trim();
    if (text.isEmpty) return;
    await widget.notifier.send(
      senderId: widget.notifier.userId,
      receiverId: widget.peerId,
      data: {'type': 'text', 'text': text},
    );
    setState(() => _messages.add('you: $text'));
    _controller.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Chat with ${widget.peerId}')),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _messages.length,
              itemBuilder: (_, i) => ListTile(title: Text(_messages[i])),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8),
            child: Row(
              children: [
                Expanded(child: TextField(controller: _controller)),
                IconButton(icon: const Icon(Icons.send), onPressed: _send),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
```

Wire `onMessage` in your app root to call `setState` when messages arrive.

***

## Expected flow

1. Start bob → `Bob online`
2. Start alice → `Alice online`
3. Alice types `Hello Bob!` → bob prints the message
4. Restart alice → `[history]` shows prior messages

***

## Troubleshooting

| Issue                       | Fix                                                 |
| --------------------------- | --------------------------------------------------- |
| Bob never receives          | Same `appId`; bob must be running                   |
| Empty history               | First conversation — history fills after first send |
| `StateError: Not connected` | Await `connect()` before send                       |

***

## Learn more

* [Building 1:1 chat](https://dnotifier.gitbook.io/product-docs/chat/building-one-to-one-chat/dart-flutter.md)
* [Chat UI patterns](https://dnotifier.gitbook.io/product-docs/chat/ui-patterns.md)
