{"slug": "ai-engineering-for-flutter-developers-ai-agents-workflows-in-flutter", "title": "AI Engineering for Flutter Developers - AI Agents & Workflows in Flutter", "summary": "A developer demonstrates how to build a multi-agent AI system in Flutter, using a Planning Agent, Generation Agent, and Validation Agent to handle complex tasks. The approach leverages Gemini API with structured output to convert vague user requests into actionable plans and generate code suggestions.", "body_md": "In the first two articles, we covered the fundamentals and how to build more reliable AI features using structured output, streaming, and proper error handling.\n\nBut there's a big limitation with single AI calls: they struggle with complex, multi-step tasks.\n\nThat's where **AI Agents** come in.\n\nToday, we're going to build a simple but powerful multi-agent system in Flutter — specifically, a **Planning Agent**, a **Generation Agent**, and a **Validation Agent**.\n\nBy the end of this video, you'll understand how to design agentic workflows and implement them in real Flutter applications.\n\nAn **AI Agent** is more like giving someone a goal and letting them think, plan, and take multiple steps to achieve it, **WHILE** a regular **LLM** call is like asking a smart person one question and getting one answer.\n\nWe'll focus on a simple and practical multi-agent pattern:\n\nThis pattern is extremely useful for real applications.\n\nWe'll build a simple Smart Feature Builder,\n\nThe user gives a high level request like: 'Create a clean Flutter logins creen with email and password validation.'\n\nThen the system works like this:\n\nThe goal of this agent is to take a vague user request and turn it into a clear, structured plan.\n\n- we define the role and system prompt for the Planning Agent\n\n- we use structured output so we can get a clean list of steps\n\n- then we create a Dart model for the plan\n\n- finally, call the agent and display the result.\n\n```\nimport 'dart:convert';\nimport 'package:googleai_dart/googleai_dart.dart';\nimport '../models/feature_plan.dart';\n\n/// Stage 1: Planning Agent\n/// Takes raw user feature requests and converts them into a structured architectural plan via Gemini API.\nclass PlanningAgent {\n  final String apiKey;\n  final String modelName;\n\n  PlanningAgent({\n    required this.apiKey,\n    this.modelName = 'gemini-3.1-flash-lite',\n  });\n\n  static const String _systemInstruction = '''\nYou are a Senior Flutter Software Architect.\nYour role is to take a high-level mobile/web feature request and generate a clean, structured architectural plan.\n\nYou must respond ONLY with a valid JSON object matching this exact schema:\n{\n  \"title\": \"String - Concise title of the feature plan\",\n  \"overview\": \"String - Executive summary of the architectural strategy\",\n  \"targetPlatform\": \"String - Target platforms (e.g. Flutter Web, iOS & Android)\",\n  \"componentsToBuild\": [\"List of String - Individual UI components, widgets, or services to build\"],\n  \"implementationSteps\": [\"List of String - Sequential step-by-step engineering tasks\"],\n  \"riskConsiderations\": [\"List of String - Potential state management, security, performance or edge case risks\"]\n}\n''';\n\n  Future<FeaturePlan> planFeature(String prompt) async {\n    if (apiKey.isEmpty) {\n      throw StateError('Gemini API Key is missing. Please configure your API key before running the pipeline.');\n    }\n\n    final config = GoogleAIConfig(authProvider: ApiKeyProvider(apiKey));\n    final client = GoogleAIClient(config: config);\n\n    final request = GenerateContentRequest(\n      contents: [Content.text('Feature Request:\\n$prompt')],\n      systemInstruction: Content.text(_systemInstruction),\n      generationConfig: const GenerationConfig(\n        responseMimeType: 'application/json',\n        temperature: 0.2,\n      ),\n    );\n\n    final response = await client.models.generateContent(\n      model: modelName,\n      request: request,\n    );\n\n    final text = response.text;\n    if (text == null || text.trim().isEmpty) {\n      throw Exception('Planning Agent returned empty response from Gemini API.');\n    }\n\n    final jsonMap = jsonDecode(text) as Map<String, dynamic>;\n    return FeaturePlan.fromJson(jsonMap);\n  }\n}\n```\n\nThis agent takes the structured plan and actually produces the output, in our case, Flutter-related code/content suggestions.\n\n- first, we create the Generation Agent with a clear role\n\n- then pass the plan from the previous agent\n\n- generate the final output\n\n- show how we keep the response structured and useful\n\n```\nimport 'dart:convert';\nimport 'package:googleai_dart/googleai_dart.dart';\nimport '../models/feature_plan.dart';\nimport '../models/generated_feature_code.dart';\n\n/// Stage 2: Generation Agent\n/// Takes the architectural FeaturePlan and user request, then generates complete, production-ready Flutter code via Gemini API.\nclass GenerationAgent {\n  final String apiKey;\n  final String modelName;\n\n  GenerationAgent({\n    required this.apiKey,\n    this.modelName = 'gemini-3.1-flash-lite',\n  });\n\n  static const String _systemInstruction = '''\nYou are an expert Lead Flutter Engineer.\nYour task is to take an Architectural Feature Plan and write production-ready, clean, well-formatted Flutter Dart code.\n\nYou must respond ONLY with a valid JSON object matching this exact schema:\n{\n  \"title\": \"String - Title of the generated feature code\",\n  \"explanation\": \"String - Clear explanation of key implementation patterns and Dart features used\",\n  \"flutterCode\": \"String - Complete, fully functioning, syntactically correct Flutter Widget Dart code\",\n  \"dependencies\": [\"List of String - Required packages in pubspec.yaml (e.g. google_fonts, flutter_animate)\"]\n}\n''';\n\n  Future<GeneratedFeatureCode> generateCode({\n    required String userPrompt,\n    required FeaturePlan plan,\n  }) async {\n    if (apiKey.isEmpty) {\n      throw StateError('Gemini API Key is missing. Please configure your API key before running the pipeline.');\n    }\n\n    final config = GoogleAIConfig(authProvider: ApiKeyProvider(apiKey));\n    final client = GoogleAIClient(config: config);\n\n    final promptInput = '''\nUser Feature Request:\n$userPrompt\n\nArchitectural Plan:\n${plan.toFormattedJson()}\n''';\n\n    final request = GenerateContentRequest(\n      contents: [Content.text(promptInput)],\n      systemInstruction: Content.text(_systemInstruction),\n      generationConfig: const GenerationConfig(\n        responseMimeType: 'application/json',\n        temperature: 0.3,\n      ),\n    );\n\n    final response = await client.models.generateContent(\n      model: modelName,\n      request: request,\n    );\n\n    final text = response.text;\n    if (text == null || text.trim().isEmpty) {\n      throw Exception('Generation Agent returned empty response from Gemini API.');\n    }\n\n    final jsonMap = jsonDecode(text) as Map<String, dynamic>;\n    return GeneratedFeatureCode.fromJson(jsonMap);\n  }\n}\n```\n\nThis agent acts like a reviewer. It checks the output from the Generation Agent for issues, missing pieces, or areas for improvement.\n\n- again, we create the Validation Agent\n\n- feed it the original request + the generated output\n\n- get structured feedback\n\n- optionally show a simple improvement loop\n\n```\nimport 'dart:convert';\nimport 'package:googleai_dart/googleai_dart.dart';\nimport '../models/feature_plan.dart';\nimport '../models/generated_feature_code.dart';\nimport '../models/validation_report.dart';\n\n/// Stage 3: Validation Agent\n/// Reviews generated code against the original user prompt and architectural plan via Gemini API.\nclass ValidationAgent {\n  final String apiKey;\n  final String modelName;\n\n  ValidationAgent({\n    required this.apiKey,\n    this.modelName = 'gemini-3.1-flash-lite',\n  });\n\n  static const String _systemInstruction = '''\nYou are a Lead Code Auditor and Security Reviewer for Flutter applications.\nYour job is to audit generated Flutter code against the user request and architectural plan.\n\nYou must evaluate code quality, completeness, error handling, accessibility, and performance.\nYou must respond ONLY with a valid JSON object matching this exact schema:\n{\n  \"qualityScore\": 92, // Integer between 0 and 100\n  \"isPassed\": true, // Boolean - true if qualityScore >= 75\n  \"identifiedIssues\": [\"List of String - Specific flaws, missing validations, or anti-patterns\"],\n  \"improvementSuggestions\": [\"List of String - Actionable code quality or performance recommendations\"],\n  \"refinedCodeSnippet\": \"String or Null - Improved/corrected snippet fixing identified issues\"\n}\n''';\n\n  Future<ValidationReport> validateOutput({\n    required String userPrompt,\n    required FeaturePlan plan,\n    required GeneratedFeatureCode generatedCode,\n  }) async {\n    if (apiKey.isEmpty) {\n      throw StateError('Gemini API Key is missing. Please configure your API key before running the pipeline.');\n    }\n\n    final config = GoogleAIConfig(authProvider: ApiKeyProvider(apiKey));\n    final client = GoogleAIClient(config: config);\n\n    final promptInput = '''\nOriginal Request:\n$userPrompt\n\nArchitectural Plan:\n${plan.toFormattedJson()}\n\nGenerated Code to Audit:\n${generatedCode.toFormattedJson()}\n''';\n\n    final request = GenerateContentRequest(\n      contents: [Content.text(promptInput)],\n      systemInstruction: Content.text(_systemInstruction),\n      generationConfig: const GenerationConfig(\n        responseMimeType: 'application/json',\n        temperature: 0.1,\n      ),\n    );\n\n    final response = await client.models.generateContent(\n      model: modelName,\n      request: request,\n    );\n\n    final text = response.text;\n    if (text == null || text.trim().isEmpty) {\n      throw Exception('Validation Agent returned empty response from Gemini API.');\n    }\n\n    final jsonMap = jsonDecode(text) as Map<String, dynamic>;\n    return ValidationReport.fromJson(jsonMap);\n  }\n}\n```\n\nWe need to connect everything into one workflow.\n\nWe will create a simple orchestrator that:\n\n1. Calls the Planning Agent\n\n2. Passes the plan to the Generation Agent\n\n3. Sends the result to the Validation Agent\n\n4. Displays the final output and feedback\n\n``` php\n/// Orchestrator Service\n/// Coordinates the multi-agent pipeline: Planning -> Generation -> Validation\nclass AgentOrchestrationService extends ValueNotifier<AgentWorkflowState> {\n\n  ...\n\n  Future<void> runWorkflow(String prompt, {required String apiKey}) async {\n    if (prompt.trim().isEmpty) return;\n\n    _addLog('Orchestrator', 'Workflow started for prompt: \"$prompt\"');\n\n    try {\n      // -----------------------------------------------------------------------\n      // STAGE 1: Planning Agent\n      // -----------------------------------------------------------------------\n      _addLog('Planning Agent', 'Analyzing request & composing architectural plan...');\n      final planningAgent = PlanningAgent(apiKey: apiKey);\n      final plan = await planningAgent.planFeature(prompt);\n\n      value = value.copyWith(\n        stage: AgentStage.generating,\n        plan: plan,\n      );\n      _addLog('Planning Agent', 'Plan generated successfully: \"${plan.title}\"', payload: plan.toFormattedJson());\n\n      // -----------------------------------------------------------------------\n      // STAGE 2: Generation Agent\n      // -----------------------------------------------------------------------\n      _addLog('Generation Agent', 'Writing Flutter code & module dependencies...');\n      final generationAgent = GenerationAgent(apiKey: apiKey);\n      final generatedCode = await generationAgent.generateCode(\n        userPrompt: prompt,\n        plan: plan,\n      );\n\n      value = value.copyWith(\n        stage: AgentStage.validating,\n        generatedCode: generatedCode,\n      );\n      _addLog('Generation Agent', 'Code generated successfully (${generatedCode.flutterCode.length} chars)', payload: generatedCode.toFormattedJson());\n\n      // -----------------------------------------------------------------------\n      // STAGE 3: Validation Agent\n      // -----------------------------------------------------------------------\n      _addLog('Validation Agent', 'Auditing code quality, security & accessibility...');\n      final validationAgent = ValidationAgent(apiKey: apiKey);\n      final validationReport = await validationAgent.validateOutput(\n        userPrompt: prompt,\n        plan: plan,\n        generatedCode: generatedCode,\n      );\n\n      _tickerTimer?.cancel();\n\n      value = value.copyWith(\n        stage: AgentStage.completed,\n        validationReport: validationReport,\n      );\n      _addLog('Validation Agent', 'Audit complete. Quality Score: ${validationReport.qualityScore}/100 (Passed: ${validationReport.isPassed})', payload: validationReport.toFormattedJson());\n      _addLog('Orchestrator', 'Multi-Agent pipeline executed successfully!');\n    } catch (e) {\n      _tickerTimer?.cancel();\n      _addLog('Orchestrator', 'Pipeline failed: $e');\n      value = value.copyWith(\n        stage: AgentStage.failed,\n        error: e,\n      );\n    }\n  }\n}\n```\n\nThe full source code is on GitHub: [github.com/techwithsam/ai_engineer_for_flutter_devs/tree/video-3](https://github.com/techwithsam/ai_engineer_for_flutter_devs/tree/video-3)\n\nQuick summary of what we covered:\n\nThis is a foundational pattern you can expand in many directions.\n\nIf you haven't already, download the free **AI Engineering Starter Pack** - I've updated it with the code and patterns from this article.\n\nHere: [techwithsam.dev/ai-starter-kit-3](https://techwithsam.dev/ai-starter-kit-3)\n\nJust enter your email, and it will be sent to you instantly.\n\nIn the next and final video of this series, we'll focus on **Production AI Engineering** - covering performance, privacy, security, evaluation, and best practices for shipping AI features in real Flutter apps.\n\nIf you found this valuable, please like and drop a comment.\n\nI'd love to know: What kind of multi-agent workflow would you like to see next?\n\nThank you for following. I'll see you in the final one.\n\nTake care!", "url": "https://wpnews.pro/news/ai-engineering-for-flutter-developers-ai-agents-workflows-in-flutter", "canonical_source": "https://dev.to/techwithsam/ai-engineering-for-flutter-developers-ai-agents-workflows-in-flutter-1cc7", "published_at": "2026-08-27 16:32:48+00:00", "updated_at": "2026-08-27 16:48:58.216161+00:00", "lang": "en", "topics": ["ai-agents", "developer-tools", "large-language-models"], "entities": ["Flutter", "Gemini", "Google AI"], "alternates": {"html": "https://wpnews.pro/news/ai-engineering-for-flutter-developers-ai-agents-workflows-in-flutter", "markdown": "https://wpnews.pro/news/ai-engineering-for-flutter-developers-ai-agents-workflows-in-flutter.md", "text": "https://wpnews.pro/news/ai-engineering-for-flutter-developers-ai-agents-workflows-in-flutter.txt", "jsonld": "https://wpnews.pro/news/ai-engineering-for-flutter-developers-ai-agents-workflows-in-flutter.jsonld"}}