generating-flutter-ui ยท diff
git:20260401.b1f912e to git:20261110.232db25
94 added, 79 removed. Audit A to A.
What this update changes in the checks
No check changed: every fixed check gives the same answer before and after this update.
A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.
---
name: "generating-flutter-ui"
- description: "Generative UI (GenUI) for Flutter using AI models like Google Gemini, Anthropic Claude, or OpenAI via the genui package. Use this skill when building dynamic AI-driven interfaces, conversational UI flows, server-rendered screen layouts, LLM-powered dashboards, chat-based UI generation, or implementing prompt-to-UI systems. Supports AI-generated widgets, reactive data binding, ContentGenerator integration, and A2uiMessageProcessor for real-time UI updates from AI responses. Ideal for apps where UI structure is determined by AI/LLM output rather than hardcoded layouts."
+ description: "Generative UI (GenUI) for Flutter with the genui 0.10 package (SurfaceController, A2uiTransportAdapter, Conversation, Surface) and an LLM backend such as Firebase AI Logic (firebase_ai). Use when the layout must come from model output, for chat-based UI generation, prompt-to-UI systems, or AI-driven dashboards. Do not use for static screens."
metadata:
- last_modified: "2026-04-01 14:35:00 (GMT+8)"
+ last_modified: "2026-11-10"
+ package_versions: "genui 0.10.4, firebase_ai 5.1.0, firebase_core 5.1.0 (verified with flutter analyze on Flutter 3.47.9)"
---
- # Flutter Generative UI (GenUI) Best Practices
+ # Flutter Generative UI (GenUI)
## Goal
- Implement a dynamic user interface generated by AI using the [genui](https://pub.dev/packages/genui) package. This is the recommended approach when an application needs to build reactive screens or components directly from AI responses without hardcoding the layout.
+ Render UI that an AI model generates at runtime, using `genui` 0.10. Use it only for features whose structure depends on model output. Static screens should use normal widgets.
## Instructions
- The `genui` package orchestrates a conversational loop between the user, the AI (via `ContentGenerator`), and the Flutter UI (via `A2uiMessageProcessor` and `DataModel`).
-
- ### 1. Project Setup
- Add the necessary packages to your `pubspec.yaml`:
+ ### 1. Setup
```bash
- flutter pub add genui
- # For Gemini integration via Firebase:
- flutter pub add genui_firebase_ai
+ flutter pub add genui firebase_ai firebase_core
```
-
- If targeting macOS/iOS, enable outbound network requests in entitlements:
- ```xml
- <key>com.apple.security.network.client</key>
- <true/>
+ - macOS and iOS: allow outbound network access in `{ios,macos}/Runner/*.entitlements` with `com.apple.security.network.client` set to `true`.
+ - Initialize Firebase and configure GenUI logging before `runApp`. `DefaultFirebaseOptions` comes from the FlutterFire CLI.
+ ```dart
+ Future<void> main() async {
+ WidgetsFlutterBinding.ensureInitialized();
+ await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
+ configureLogging(logCallback: (level, msg) => debugPrint('GenUI $level: $msg'));
+ runApp(const MaterialApp(home: GenUiPage()));
+ }
```
- ### 2. Core Integration Structure
-
- To connect your Flutter application to the AI agent, you need to instantiate three main components:
-
- 1. **`A2uiMessageProcessor`**: Handles the UI side, translating AI messages into UI actions. Supply it with a `Catalog` of widgets the AI is allowed to use.
- 2. **`ContentGenerator`**: Handles communication with the AI. Supply it with system instructions and tools.
- 3. **`GenUiConversation`**: The facade coordinating the processor and generator.
+ ### 2. Core objects
- **Example Setup in a StatefulWidget:**
+ | Object | Role |
+ |---|---|
+ | `SurfaceController(catalogs: [...])` | Holds the widget catalog and the state of each surface. |
+ | `A2uiTransportAdapter(onSend: ...)` | Sends user messages to the model. Feed model output back with `addChunk(text)`. |
+ | `Conversation(controller:, transport:)` | Runs the loop. Exposes `events` and `sendRequest(ChatMessage)`. |
+ | `Surface(surfaceContext: controller.contextFor(id))` | Renders one surface. |
+ ### 3. Example: Firebase AI Logic backend
+ This file compiles with `flutter analyze` against the pinned versions.
```dart
+ import 'package:firebase_ai/firebase_ai.dart';
import 'package:flutter/material.dart';
- import 'package:genui/genui.dart';
- import 'package:genui_firebase_ai/genui_firebase_ai.dart';
+ import 'package:genui/genui.dart' hide TextPart;
+ import 'package:genui/genui.dart' as genui;
- class GenUIPage extends StatefulWidget {
- const GenUIPage({super.key});
+ class GenUiPage extends StatefulWidget {
+ const GenUiPage({super.key});
@override
- State<GenUIPage> createState() => _GenUIPageState();
+ State<GenUiPage> createState() => _GenUiPageState();
}
- class _GenUIPageState extends State<GenUIPage> {
- late final A2uiMessageProcessor _a2uiMessageProcessor;
- late final GenUiConversation _genUiConversation;
+ class _GenUiPageState extends State<GenUiPage> {
+ late final SurfaceController _controller;
+ late final A2uiTransportAdapter _transport;
+ late final Conversation _conversation;
+ late final ChatSession _chatSession;
+ final List<String> _surfaceIds = [];
@override
void initState() {
super.initState();
+ final catalog = BasicCatalogItems.asCatalog();
+ _controller = SurfaceController(catalogs: [catalog]);
+ _transport = A2uiTransportAdapter(onSend: _sendAndReceive);
+ _conversation = Conversation(controller: _controller, transport: _transport);
+ final model = FirebaseAI.googleAI().generativeModel(model: 'gemini-3-flash-preview');
+ _chatSession = model.startChat();
- // 1. Initialize Message Processor with predefined catalog widgets
- _a2uiMessageProcessor = A2uiMessageProcessor(
- catalogs: [CoreCatalogItems.asCatalog()],
- );
+ _conversation.events.listen((event) {
+ switch (event) {
+ case ConversationSurfaceAdded added:
+ setState(() => _surfaceIds.add(added.surfaceId));
+ case ConversationSurfaceRemoved removed:
+ setState(() => _surfaceIds.remove(removed.surfaceId));
+ case ConversationContentReceived content:
+ debugPrint(content.text);
+ case ConversationError error:
+ debugPrint('${error.error}');
+ default:
+ }
+ });
- // 2. Initialize Content Generator (e.g., Firebase AI / Gemini)
- final contentGenerator = FirebaseAiContentGenerator(
- catalog: CoreCatalogItems.asCatalog(),
- systemInstruction: '''
- You are an AI assistant. You must generate UI by responding with JSON
- matching the provided widget schemas. Always output valid UI structures.
- ''',
- tools: _a2uiMessageProcessor.getTools(),
+ final promptBuilder = PromptBuilder.chat(
+ catalog: catalog,
+ systemPromptFragments: ['You are a helpful assistant.'],
);
+ _conversation.sendRequest(ChatMessage.system(promptBuilder.systemPromptJoined()));
+ }
- // 3. Orchestrate the Conversation
- _genUiConversation = GenUiConversation(
- a2uiMessageProcessor: _a2uiMessageProcessor,
- contentGenerator: contentGenerator,
- // Implement your handlers for rendering generated surfaces
- onSurfaceAdded: (surfaceId) { /* Handle surface creation */ },
- onSurfaceDeleted: (surfaceId) { /* Handle surface deletion */ },
- onTextResponse: (text) { /* Optional: show text explicitly */ },
- onError: (error) { /* Handle generation errors */ },
- );
+ Future<void> _sendAndReceive(ChatMessage msg) async {
+ final buffer = StringBuffer();
+ for (final part in msg.parts) {
+ if (part.isUiInteractionPart) {
+ buffer.write(part.asUiInteractionPart!.interaction);
+ } else if (part is genui.TextPart) {
+ buffer.write(part.text);
+ }
+ }
+ if (buffer.isEmpty) return;
+ final response = await _chatSession.sendMessage(Content.text(buffer.toString()));
+ if (response.text?.isNotEmpty ?? false) {
+ _transport.addChunk(response.text!);
+ }
}
@override
- void dispose() {
- _genUiConversation.dispose();
- super.dispose();
+ Widget build(BuildContext context) {
+ return Column(children: [
+ for (final id in _surfaceIds) Surface(surfaceContext: _controller.contextFor(id)),
+ ]);
}
@override
- Widget build(BuildContext context) {
- // UI Implementation interacting with _genUiConversation.sendRequest()
- return const Scaffold();
+ void dispose() {
+ _conversation.dispose();
+ super.dispose();
}
}
```
- ### 3. Data Model & Data Binding
-
- A core philosophy of `genui` is utilizing a central `DataModel`. Widgets don't manage their own dynamic state; instead, they bind to paths within the `DataModel`.
-
- When creating custom widgets to add to your `Catalog`, ensure they react to the data context:
+ ### 4. Events
+ Handle `ConversationSurfaceAdded` and `ConversationSurfaceRemoved` by updating the list of surface IDs, then build one `Surface` per ID. Handle `ConversationContentReceived` for plain text and `ConversationError` for failures.
- ```dart
- // The AI will generate JSON like:
- // { "Text": { "text": { "literalString": "Hello" } } }
- // OR
- // { "Text": { "text": { "path": "/user/welcome_message" } } }
- ```
- * **literalString**: Static data directly from the AI.
- * **path**: A reference to a location in the `DataModel`. Updates to this path automatically rebuild any widgets bound to it. Input widgets (like `TextField`) should directly update this `DataModel`.
+ ### 5. System prompt
+ Build the prompt with `PromptBuilder.chat(catalog:, systemPromptFragments:)`, then send `ChatMessage.system(promptBuilder.systemPromptJoined())` once. `systemPrompt()` is a method that returns an `Iterable<String>`, not a `String`.
- ### 4. Customizing the Catalog
+ ### 6. Ask about input widgets
+ Before you write user-input UI, ask which widgets the app should use. The official guide treats this as a question for the user, not a default.
- To extend GenUI beyond the `CoreCatalogItems`, define your own `CatalogItem`s and provide them to both the `A2uiMessageProcessor` and the `ContentGenerator`. This tells the AI what Custom Widgets are available and what parameters they accept.
+ ### 7. Official reference
+ The `genui` package ships an official integration guide at `skills/integrate-genui-firebase/SKILL.md` inside the installed package. Read it when you need the full Firebase setup steps.
## Constraints
-
- * **Architecture Scope**: Do not use `genui` for static screens or standard layouts. It should be reserved exclusively for features needing generative or highly dynamic, AI-driven UI presentation.
- * **State Management**: Within GenUI components, prefer the unified `DataModel` reactivity over local `setState` for data shared with the AI.
- * **Error Handling**: Always ensure `onError` in `GenUiConversation` is handled appropriately, as AI responses can sometimes fail parsing or violate catalog schemas.
+ - Do not add `genui_firebase_ai`. It is discontinued. Call `firebase_ai` directly from `onSend`.
+ - Do not use the 0.7-era names `ContentGenerator`, `GenUiConversation`, `A2uiMessageProcessor`, or the manual `DataModel` wiring. They do not match genui 0.10.4.
+ - Dispose the `Conversation` in `dispose()`.
+ - Use GenUI only for AI-driven structure. Do not use it for static screens or ordinary layouts.