【文章翻譯】Build full-stack agentic UI with Dart, Flutter, and Genkit

【文章內容使用 Gemini 2.5 Flash 自動翻譯產生】

原文:https://flutter.dev/blog/full-stack-agentic-ui-genkit-dart-a2ui

使用 Dart、Flutter 和 Genkit 建構全端代理 UI

用 Genkit Dart、A2UI 和 Flutter 建構端到端的餐廳服務應用程式,從 Dart 伺服器串流經過驗證的原生 UI 介面。

作者:Chris Gill
2026 年 11 月 24 日 · 10 分鐘閱讀

Build full-stack agentic UI with Dart, Flutter, and Genkit banner featuring the Genkit, Dart, Flutter, and A2UI logos.

當 AI 代理協助預訂餐桌、篩選航班或自訂訂單時,互動式小工具比純文字來回打字更有效率。生成式使用者介面 (GenUI) 將日期選擇器、滑桿和確認卡片等原生控制項直接放在對話中。

A2UI (Agent-to-User Interface) 是 Google 用於代理驅動介面的開放協定。代理會串流結構化的 UI 介面,而不是回傳原始文字,而客戶端則使用原生小工具來渲染它們,並將使用者互動作為事件回傳。

藉助 Genkit Dart 和 A2UI,您可以使用 Dart 和 Flutter 建構具有代理 UI 的全端應用程式,從後端工具到互動式螢幕。本逐步解說將為 Cymbal Bistro 建構一個端到端的餐廳服務應用程式(請參閱 GitHub 上的完整範例)。

Flutter 客戶端渲染互動式 A2UI 介面,同時 Genkit Dart 代理檢查可用性並確認預訂。

為何使用 Genkit Dart 建構代理 UI

Genkit 是 Google 的開源框架,用於在 Dart 中建構 AI 工作流程和有狀態代理。當您將其與 A2UI 結合使用時,您會得到:

  • 端到端 Dart 工具: 在 Dart 中定義類型化的工具綱要,使用 defineAgent 保持多回合狀態,並使用 remoteAgent 透過 HTTP 將回應串流到 Flutter。
  • 可交換的模型和中介軟體: 透過一個 API 在 Google、Anthropic、OpenAI 和本地提供者的模型之間切換,並附加 A2UI 中介軟體,而不會將 UI 格式混合到您的工具邏輯中。
  • 本地 UI 檢查和測試: 在連接您的 Flutter 螢幕之前,在 Genkit 開發人員 UI 中預覽生成的介面,檢查元件樹和綁定資料,並模擬點擊。

A2UI 如何在 Genkit Dart 中運作

Genkit 的 A2UI 整合圍繞三個概念協調您的伺服器和 Flutter 應用程式之間的動態 UI:

  1. 經批准的元件目錄: 您為代理提供一個受信任的小工具目錄,從 A2UI 的 18 個元件基本目錄(例如 Card、DateTimeInput、ChoicePicker、Slider、Tabs 和 Modal)開始。由於代理只能從您批准的元件中選擇,而不是輸出原始 HTML 或腳本,因此您的 Flutter 應用程式可以控制樣式和安全性,而 API 金鑰和後端變更則保留在伺服器上。
  2. 內建 A2UI 1.0 增強功能: A2UI 中介軟體預設使用 A2UI 1.0 中的增強功能,包括 A2UI Express,與原始 JSON 相比,生成的 UI 輸出大約減少了一半。由於中介軟體會在伺服器上將每個區塊編譯為標準 A2UI JSON,針對您的目錄進行驗證,並在錯誤時重試,因此您可以獲得更快的串流和更可靠的渲染。
  3. 就地更新和動作事件: 每個渲染的介面都有一個 surfaceId。您的 Flutter 應用程式會原生渲染每個介面,每當相同的 surfaceId 再次到達時就地更新現有卡片,並將按鈕點擊或表單提交作為結構化動作事件回傳到伺服器。
Genkit Dart and Flutter A2UI architecture showing a Flutter app exchanging prompts, action messages, and A2UI JSON streams with a Genkit Dart server
Flutter 應用程式、Shelf HTTP 伺服器、A2UI 中介軟體和 Genkit Dart 代理之間的端到端流程圖。

設定全端專案

若要跟隨,請安裝 Flutter (使用 Dart 3.12 或更高版本) 和 Genkit CLI,並設定 GEMINI_API_KEY 環境變數。呼叫 Gemini 模型可能會產生超出免費額度的使用費。

將伺服器和 Flutter 應用程式保留在單獨的套件中(dart create server 和 flutter create client),這樣後端中介軟體就不會混入客戶端建置中,然後添加它們的依賴項:

1
2
3
4
5
6
# Server package (server/)
dart pub add genkit genkit_a2ui genkit_google_genai genkit_shelf schemantic shelf shelf_router
dart pub add --dev build_runner schemantic_builder

# Flutter client package (client/)
flutter pub add genkit a2ui_flutter a2ui_core json_schema_builder url_launcher

定義伺服器端代理

在此範例中,uiAgent 為 Cymbal Bistro 提供餐飲服務。當顧客要求一張餐桌時,uiAgent 會呼叫 checkAvailability 並串流互動式預訂卡。當顧客提交預訂時,uiAgent 會呼叫 confirmReservation 並將表單就地替換為 ConfirmationPass 卡。

在 server/lib/agent.dart 中定義工具綱要、工具和代理,並附加 A2UI 中介軟體,以便模型可以串流 UI 介面。之後運行 dart run build_runner build 以生成 agent.g.dart:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// server/lib/agent.dart
import 'package:genkit/experimental.dart';
import 'package:genkit/genkit.dart';
import 'package:genkit_a2ui/a2ui.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';
import 'package:schemantic/schemantic.dart';

import 'shared.dart';

part 'agent.g.dart';

@Schema()
abstract class $CheckAvailabilityInput {
@Field(description: 'The restaurant name, e.g. Cymbal Bistro.')
String get restaurant;

@Field(description: 'The date for the reservation, e.g. tonight, tomorrow, or YYYY-MM-DD.')
String get date;

@Field(description: 'Number of guests.')
int get partySize;
}

@Schema()
abstract class $CheckAvailabilityOutput {
String get restaurant;
String get date;
int get partySize;
bool get available;
List<String> get availableSlots;
List<String> get seatingAreas;
}

// ConfirmReservationInput, ConfirmReservationOutput, and _resolveIsoDate omitted for brevity.

// Register plugins on the shared Genkit instance
final Genkit ai = Genkit(plugins: [googleAI(), A2uiPlugin()]);

// Tool 1: Check table availability and open time slots
final checkAvailability = ai.defineTool(
name: 'checkAvailability',
description: 'Checks table availability, open time slots, and seating areas for a restaurant.',
inputSchema: CheckAvailabilityInput.$schema,
outputSchema: CheckAvailabilityOutput.$schema,
fn: (input, _) async {
return .response(
CheckAvailabilityOutput(
restaurant: input.restaurant.isEmpty ? 'Cymbal Bistro' : input.restaurant,
date: _resolveIsoDate(input.date),
partySize: input.partySize,
available: true,
availableSlots: const ['6:00 PM', '6:30 PM', '7:00 PM', '7:30 PM', '8:00 PM'],
seatingAreas: const ['Indoor Dining', 'Heated Patio', 'Chef\'s Counter'],
),
);
},
);

// Tool 2: Confirm a reservation and issue a confirmation code
final confirmReservation = ai.defineTool(
name: 'confirmReservation',
description: 'Books and confirms a dining reservation, returning a confirmation code.',
inputSchema: ConfirmReservationInput.$schema,
outputSchema: ConfirmReservationOutput.$schema,
fn: (input, _) async {
final resolvedDate = _resolveIsoDate(input.date);
final seed = (resolvedDate.hashCode ^ input.time.hashCode ^ input.partySize).abs();
return .response(
ConfirmReservationOutput(
confirmationCode: 'CB-${1000 + (seed % 9000)}',
restaurant: input.restaurant.isEmpty ? 'Cymbal Bistro' : input.restaurant,
date: resolvedDate,
time: input.time,
partySize: input.partySize,
seatingArea: input.seatingArea ?? 'Indoor Dining',
specialRequests: input.specialRequests ?? 'None',
status: 'Confirmed',
),
);
},
);

// Define the stateful agent with the a2ui middleware attached
final uiAgent = ai.defineAgent(
name: 'uiAgent',
model: googleAI.gemini('gemini-4-hydrogen'),
system:
'You are the dining concierge for Cymbal Bistro. Keep text responses brief.\n'
'Use checkAvailability before rendering a reservation card, and use '
'confirmReservation when the user submits their booking to replace the '
'same surface with a ConfirmationPass card showing their confirmation code.',
tools: [checkAvailability, confirmReservation],
use: [a2ui(catalog: bistroCatalogId, validate: 'warn')],
store: InMemorySessionStore(),
);

在這裡,bistroCatalogId 指向在 擴展元件目錄 中定義的自訂目錄。如果您只需要 18 個內建元件,請省略 catalog 參數。對於 Google Cloud 部署,將 googleAI 替換為 Vertex AI plugin 並呼叫 vertexAI.gemini('gemini-4-hydrogen')。

透過 HTTP 提供代理

在 server/bin/server.dart 中透過 HTTP 公開 uiAgent。GenkitRouter 會自動將串流、快照和取消路由安裝在 Shelf 路由器上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// server/bin/server.dart
import 'package:genkit/experimental_io.dart';
import 'package:genkit/io.dart';
import 'package:genkit_shelf/genkit_shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_router/shelf_router.dart';

import 'package:a2ui_reservations_server/agent.dart';

Future<void> main() async {
await registerCatalogs();

// Mounts /uiAgent, /uiAgent/getSnapshot, and /uiAgent/abort
final genkit = GenkitRouter()..addAgent(uiAgent);
final app = Router()
..mount(
'/api/',
genkit.asShelfHandler(
cors: const CorsOptions(
allowedHeaders: ['Content-Type', 'Accept', 'X-Genkit-Stream-Id'],
),
),
);

await io.serve(app.call, 'localhost', 8080);
}

在 Flutter 中渲染串流介面

在 client/lib/main.dart 中,remoteAgent 會從您的伺服器串流回應,而 MessageProcessor 會將傳入的 A2UI 負載轉換為即時的 A2uiSurface Widget。兩個線路輔助函數(a2uiMessagesFrom 和 a2uiActionToMessage)位於 樣本儲存庫 的 client/lib/a2ui_helpers.dart 中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// client/lib/main.dart
import 'package:a2ui_core/a2ui_core.dart';
import 'package:a2ui_flutter/a2ui_flutter.dart';
import 'package:flutter/material.dart';
import 'package:genkit/experimental_client.dart';

import 'a2ui_helpers.dart';
import 'catalog.dart';

class _ChatPageState extends State<ChatPage> {
late final AgentApi _agent = remoteAgent(
url: 'http://localhost:8080/api/uiAgent',
getSnapshotUrl: 'http://localhost:8080/api/uiAgent/getSnapshot',
abortUrl: 'http://localhost:8080/api/uiAgent/abort',
);
late final AgentChat _chat = _agent.chat();
late final MessageProcessor<ComponentImplementation> _processor =
MessageProcessor(
catalogs: [bistroClientCatalog],
unifiedOutbound: true,
outboundListener: _onRendererMessage,
onError: (error) => debugPrint('A2UI renderer error: ${error.message}'),
);
final List<String> _surfaceIds = [];

@override
void initState() {
super.initState();
// Track each created surface by surface.id; replacements with the same id
// update in place rather than appending a duplicate card.
_processor.model.onSurfaceCreated.subscribe((surface) {
if (!mounted) return;
if (!_surfaceIds.contains(surface.id)) {
setState(() => _surfaceIds.add(surface.id));
} else {
setState(() {});
}
});
_processor.model.onSurfaceDeleted.subscribe((_) {
if (mounted) setState(() {});
});
}

Future<void> _runTurn(AgentTurn turn) async {
await for (final chunk in turn.stream) {
// 1. Append streamed prose text deltas
if (chunk.text.isNotEmpty) {
_appendProseDelta(chunk.text);
}

// 2. Feed streamed A2UI messages into the MessageProcessor
for (final m in a2uiMessagesFrom(chunk.raw.modelChunk?.content)) {
try {
_processor.processMessages([m]);
} on Object catch (err) {
debugPrint('Failed to apply A2UI message: $err');
}
}
}
await turn.response;
}

Widget _buildSurface(String surfaceId) {
final surface = _processor.model.getSurface(surfaceId);
if (surface == null) return const SizedBox.shrink();
return A2uiSurface(key: ObjectKey(surface), surface: surface);
}
}

處理互動式使用者動作

當顧客選擇他們的選項並點擊 確認預訂 時,渲染器會發出一個帶有綁定表單值的 ActionMessage。將其作為下一個回合轉發給 uiAgent:

1
2
3
4
5
6
7
// client/lib/main.dart
Future<void> _onRendererMessage(RendererToAgentMessage message) async {
if (message is! ActionMessage || _busy) return;

// Forward the user's UI interaction back to the agent as the next turn
await _runTurn(_chat.sendStream(message: a2uiActionToMessage(message)));
}

在連線上,a2uiActionToMessage 會將 A2UI action 負載包裝在 DataPart (application/a2ui+json) 中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"messages": [
{
"version": "1.0",
"action": {
"name": "confirmReservation",
"surfaceId": "cymbal-bistro-reservation",
"sourceComponentId": "confirmBtn",
"timestamp": "2026-11-14T00:29:44.755489Z",
"context": {
"restaurant": "Cymbal Bistro",
"date": "2026-11-14",
"time": ["7:30 PM"],
"partySize": 4,
"seatingArea": ["Heated Patio"],
"specialRequests": ""
}
}
}
]
}

uiAgent 接收此事件,呼叫 confirmReservation,並重複使用相同的介面 ID,將預訂表單就地替換為 ConfirmationPass 卡:

Two-turn Cymbal Bistro Flutter flow showing Basic Catalog inputs in Turn 1 replaced in place by a custom ConfirmationPass widget in Turn 2
第一回合渲染基本目錄輸入,第二回合就地更新相同的介面為自訂的 ConfirmationPass 小工具。

擴展元件目錄

A2UI 的 basicCatalog 開箱即用包含 18 個常見的佈局、媒體和輸入元件。當您需要自訂品牌或領域小工具時,請在伺服器端擴展它:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// server/lib/shared.dart
const String bistroCatalogId = 'com.example.a2ui.bistro';

// server/lib/agent.dart
final A2uiCatalog bistroCatalog = basicCatalog.extend(
id: bistroCatalogId,
components: [
A2uiCatalogComponent.simple(
name: 'ConfirmationPass',
description:
'Displays a highlighted dining confirmation pass with the booking '
'confirmation code and reservation summary once a table is booked.',
params: [
const A2uiParam.dynamicValue(
'confirmationCode',
required: true,
description: 'Reservation confirmation code, e.g. CB-4821.',
),
const A2uiParam.dynamicValue(
'summary',
required: true,
description: 'Formatted date, time, party size, and seating preference.',
),
],
),
],
);

Future<void> registerCatalogs() =>
loadCatalog(ai, id: bistroCatalogId, catalog: bistroCatalog);

在 Flutter 客戶端上,在相同的 bistroCatalogId 下註冊一個與 ConfirmationPass 相符的 Flutter widget 以及 BasicComponents.all(請參閱 範例儲存庫 中的 client/lib/catalog.dart):

Mapping the 18-component Basic Catalog and custom ConfirmationPass schema to native Flutter widgets with CatalogImplementation
將 18 個內建的基本目錄小工具與自訂的 ConfirmationPass 元件在 bistroCatalogId 下合併。

您還可以從 A2UI 生態系統中插入現有的領域目錄,例如 Google Maps Platform Agentic UI toolkit。

在開發人員 UI 中檢查和調試 A2UI 工作流程

在 Genkit CLI 下啟動您的 Dart 伺服器,以便在 Genkit 開發人員 UI 中本地測試和檢查多回合 A2UI 工作流程:

1
genkit start -- dart run bin/server.dart

開發人員 UI 會將串流的 UI 區塊折疊成互動式的 A2UI Surface 卡片,因此您可以在連接 Flutter 之前測試多回合流程。點擊 檢查 以打開 A2UI Surface Inspector 並查看即時預覽以及 元件樹、活動資料模型 和驗證狀態。

您還可以透過點擊預覽控制項或選擇 模擬動作 來直接在瀏覽器中測試互動,以將自訂動作負載回傳給代理。對於更深入的偵錯,請在 追蹤檢視器 中逐步執行工具呼叫,並在 日誌 抽屜中檢查執行時日誌。

Inspecting a live reservation card, hierarchical component tree, and active data model in the Genkit Developer UI Surface Inspector
在 Genkit 開發人員 UI 中檢查渲染的預訂介面、其元件階層和綁定資料模型值。

下一步

借助 Genkit Dart、A2UI 和 Flutter,您可以從單一 Dart 程式碼庫建立後端代理,並在所有平台上串流原生、經過驗證的 UI 介面。

欲進一步探索:

更多 Flutter 文章

發佈 A2UI 1.0 和 a2ui_flutter

為 Flutter 提供更快、更安全、更模組化的生成式 UI

Andrew Brogdon Vishal Prabhu Motwani
Andrew Brogdon, Vishal Prabhu Motwani
2026 年 11 月 17 日 · 8 分鐘閱讀

發佈穩定的直接原生互通性

FFIgen for Objective-C 和 JNIgen for Java/Kotlin 現已穩定,Pigeon 使它們發揮作用,讓您的 Plugin 可以直接呼叫原生程式碼

Mariam Hasnany
Mariam Hasnany
2026 年 11 月 12 日 · 6 分鐘閱讀