> 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/workflows-and-agents/example-multi-agent/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 **blog article writer** workflow with three sequential agents.

## Complete runnable example

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

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

// ── Agent 1: Content creator ────────────────────────────────────────

final contentCreatorAgent = defineAgent(
  name: 'content-creator',
  run: (ctx) async {
    final brief = ctx.input as Map<String, dynamic>;
    final keywords = (brief['keywords'] as List?)?.cast<String>() ?? [];

    if (brief['topic'] == null) {
      throw WorkflowError('content-creator: topic is required',
          agentName: 'content-creator');
    }

    final aiResponse = await ctx.sendAI(
      message: {
        'useKnowledgeBase': false,
        'messages': [
          {
            'role': 'system',
            'content': '''You are an expert blog writer. Write a complete first-draft article in markdown.
Requirements:
- Target audience: ${brief['audience'] ?? 'general'}
- Tone: ${brief['tone'] ?? 'neutral'}
- Approximate length: ${brief['wordCount'] ?? 800} words
- Include an engaging introduction, clear H2/H3 headings, and a conclusion.
Return only the article body in markdown.''',
          },
          {
            'role': 'user',
            'content':
                'Topic: ${brief['topic']}${keywords.isNotEmpty ? '\nSuggested keywords: ${keywords.join(', ')}' : ''}',
          },
        ],
      },
      saveHistory: false,
      label: 'Blog content creation',
    );

    final content = extractAiContent(aiResponse);
    ctx.state['draft'] = content;
    return {'content': content, 'stage': 'content_creation'};
  },
);

// ── Agent 2: Clarity editor ─────────────────────────────────────────

final clarityEditorAgent = defineAgent(
  name: 'clarity-editor',
  run: (ctx) async {
    final input = ctx.input;
    final draft = input is Map
        ? input['content']?.toString()
        : ctx.state['draft']?.toString();

    if (draft == null || draft.trim().isEmpty) {
      throw WorkflowError('clarity-editor: no draft to refine',
          agentName: 'clarity-editor');
    }

    final aiResponse = await ctx.sendAI(
      message: {
        'useKnowledgeBase': false,
        'messages': [
          {
            'role': 'system',
            'content':
                'You are an editorial clarity specialist. Improve the draft for readability and flow. Preserve facts and markdown formatting. Return only the revised article.',
          },
          {'role': 'user', 'content': draft},
        ],
      },
      saveHistory: false,
      label: 'Blog clarity editing',
    );

    final content = extractAiContent(aiResponse);
    ctx.state['refined'] = content;
    return {'content': content, 'stage': 'clarity'};
  },
);

// ── Agent 3: SEO optimizer ──────────────────────────────────────────

final seoOptimizerAgent = defineAgent(
  name: 'seo-optimizer',
  run: (ctx) async {
    final input = ctx.input as Map<String, dynamic>? ?? {};
    final article =
        input['content']?.toString() ?? ctx.state['refined']?.toString() ?? '';
    final brief = ctx.state['blogBrief'] as Map<String, dynamic>? ?? {};
    final topic = input['topic']?.toString() ?? brief['topic']?.toString() ?? '';
    final keywords =
        (input['keywords'] as List?)?.cast<String>() ??
        (brief['keywords'] as List?)?.cast<String>() ??
        [];

    if (article.trim().isEmpty) {
      throw WorkflowError('seo-optimizer: no article to optimize',
          agentName: 'seo-optimizer');
    }

    final aiResponse = await ctx.sendAI(
      message: {
        'useKnowledgeBase': false,
        'messages': [
          {
            'role': 'system',
            'content': '''You are an SEO content optimizer. Return JSON only:
{
  "content": "optimized markdown article",
  "metaTitle": "string",
  "metaDescription": "string",
  "slug": "string",
  "keywords": ["string"]
}''',
          },
          {
            'role': 'user',
            'content':
                'Topic: $topic\nTarget keywords: ${keywords.isNotEmpty ? keywords.join(', ') : 'derive from topic'}\nArticle: $article',
          },
        ],
      },
      saveHistory: false,
      label: 'Blog SEO optimization',
    );

    final raw = extractAiContent(aiResponse);
    Map<String, dynamic> parsed;
    try {
      parsed = jsonDecode(raw) as Map<String, dynamic>;
    } catch (_) {
      parsed = {
        'content': raw,
        'metaTitle': topic,
        'metaDescription': '',
        'slug': topic.toLowerCase().replaceAll(RegExp(r'\s+'), '-'),
        'keywords': keywords,
      };
    }

    final content = parsed['content']?.toString() ?? raw;
    ctx.state['final'] = content;
    return {
      'content': content,
      'metaTitle': parsed['metaTitle'] ?? topic,
      'metaDescription': parsed['metaDescription'] ?? '',
      'slug': parsed['slug'] ?? '',
      'keywords': parsed['keywords'] ?? keywords,
      'stage': 'seo',
    };
  },
);

// ── Workflow ────────────────────────────────────────────────────────

Future<dynamic> blogArticleEntry(WorkflowContext ctx) async {
  final brief = ctx.input as Map<String, dynamic>;
  ctx.state['blogBrief'] = brief;

  final creation = await ctx.runAgent('content-creator');
  ctx.state['stage'] = 'content_creation';

  final clarity = await ctx.runAgent(
    'clarity-editor',
    input: {'content': (creation as Map)['content']},
  );
  ctx.state['stage'] = 'clarity';

  final seo = await ctx.runAgent(
    'seo-optimizer',
    input: {
      'content': (clarity as Map)['content'],
      'topic': brief['topic'],
      'keywords': brief['keywords'],
    },
  );
  ctx.state['stage'] = 'seo';

  return {
    'article': seo['content'],
    'seo': {
      'metaTitle': seo['metaTitle'],
      'metaDescription': seo['metaDescription'],
      'slug': seo['slug'],
      'keywords': seo['keywords'],
    },
    'stages': {
      'contentCreation': creation['content'],
      'clarity': clarity['content'],
      'seo': seo['content'],
    },
  };
}

final blogArticleWorkflow = Workflow(
  name: 'blog-article-writer',
  description: 'Three-step blog pipeline: create, clarify, SEO',
  observability: true,
  entry: blogArticleEntry,
)
  ..registerAgents({
    'content-creator': contentCreatorAgent,
    'clarity-editor': clarityEditorAgent,
    'seo-optimizer': seoOptimizerAgent,
  });

// ── Runner ──────────────────────────────────────────────────────────

const userId = 'blog-pipeline';

Future<void> main() async {
  final notifier = DNotifier(
    appId: 'your-app-id',
    secret: 'your-app-secret',
    transport: 'http',
    userId: userId,
    onConnected: () => print('Connected'),
    onMessage: (_) {},
  );

  await notifier.connect();

  final run = await notifier.runWorkflow(
    workflow: blogArticleWorkflow,
    input: {
      'topic': 'How to build deterministic AI workflows with DNotifier',
      'keywords': ['workflow', 'sdk', 'observability'],
      'audience': 'software developers',
      'tone': 'professional',
      'wordCount': 900,
    },
  );

  print('Execution: ${run.executionId}');
  final result = run.result;
  if (result is Map) {
    print('Meta title: ${result['seo']?['metaTitle']}');
    final article = result['article']?.toString() ?? '';
    print('Article preview: ${article.length > 300 ? article.substring(0, 300) : article}');
  }
}
```

## Learn more

* [**Workflow observability**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/observability.md)
* [**Build a workflow**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/build-workflow/dart-flutter.md)
