> 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/ai/example-ai-assistant/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

Self-contained **Dart HTTP server** assistant with per-user **session** storage.

## Complete example

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

const serviceUserId = 'api-assistant';

final sessions = <String, String>{};

late final DNotifier notifier;

Future<void> main() async {
  notifier = DNotifier(
    appId: Platform.environment['DNOTIFIER_APP_ID']!,
    secret: Platform.environment['DNOTIFIER_SECRET']!,
    transport: 'http',
    userId: serviceUserId,
    logs: true,
    onConnected: () => print('AI service ready'),
    onMessage: (_) {},
  );

  await notifier.connect();

  final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 3000);
  print('Assistant API on :3000');

  await for (final request in server) {
    if (request.method == 'POST' && request.uri.path == '/api/chat') {
      await _handleChat(request);
    } else if (request.method == 'DELETE' &&
        request.uri.path.startsWith('/api/chat/')) {
      final userId = request.uri.pathSegments.last;
      sessions.remove(userId);
      request.response.statusCode = HttpStatus.noContent;
      await request.response.close();
    } else {
      request.response.statusCode = HttpStatus.notFound;
      await request.response.close();
    }
  }
}

Future<void> _handleChat(HttpRequest request) async {
  final body = await utf8.decoder.bind(request).join();
  final json = jsonDecode(body) as Map<String, dynamic>;
  final userId = json['userId']?.toString();
  final message = json['message']?.toString();

  if (userId == null || message == null) {
    request.response.statusCode = HttpStatus.badRequest;
    request.response.write(jsonEncode({'error': 'userId and message required'}));
    await request.response.close();
    return;
  }

  final existingSession = sessions[userId];

  final response = await notifier.sendAI(
    senderId: userId,
    sessionId: existingSession,
    message: {
      'messages': [
        {
          'role': 'system',
          'content':
              'You are a friendly product assistant. Be concise and accurate.',
        },
        {'role': 'user', 'content': message},
      ],
    },
    saveHistory: true,
  );

  if (existingSession == null) {
    final newSession = _sessionIdFromResponse(response);
    if (newSession != null) sessions[userId] = newSession;
  }

  request.response.headers.contentType = ContentType.json;
  request.response.write(jsonEncode({
    'answer': _extractContent(response),
    'sessionId': sessions[userId],
  }));
  await request.response.close();
}

String _extractContent(dynamic response) {
  if (response is Map && response['data'] is Map) {
    return response['data']['content']?.toString() ?? '';
  }
  return response.toString();
}

String? _sessionIdFromResponse(dynamic response) {
  if (response is Map) {
    final meta = response['metadata'];
    if (meta is Map) {
      final packet = meta['packet'];
      if (packet is Map) return packet['id']?.toString();
      return meta['id']?.toString();
    }
  }
  return null;
}
```

## Flutter client snippet

```dart
Future<Map<String, dynamic>> askAssistant(String message) async {
  final client = HttpClient();
  final req = await client.postUrl(Uri.parse('http://localhost:3000/api/chat'));
  req.headers.contentType = ContentType.json;
  req.write(jsonEncode({'userId': 'user-alice', 'message': message}));
  final res = await req.close();
  final body = await utf8.decoder.bind(res).join();
  return jsonDecode(body) as Map<String, dynamic>;
}
```

## Learn more

* [**Sessions**](https://dnotifier.gitbook.io/product-docs/ai/sessions/dart-flutter.md)
* [**Example: RAG bot**](https://dnotifier.gitbook.io/product-docs/ai/example-rag-bot/dart-flutter.md)
