1. บทนำ
ใน Codelab นี้ คุณจะสร้างแอปรายการงานโดยใช้ Flutter, Firebase AI Logic และแพ็กเกจ genui ใหม่ คุณจะเริ่มต้นด้วยแอปแชทแบบข้อความ อัปเกรดด้วย GenUI เพื่อให้ Agent สามารถสร้าง UI ของตนเองได้ และสุดท้ายสร้างคอมโพเนนต์ UI แบบอินเทอร์แอกทีฟที่กำหนดเองซึ่งคุณและ Agent สามารถจัดการได้โดยตรง

สิ่งที่คุณต้องทำ
- สร้างอินเทอร์เฟซแชทพื้นฐานโดยใช้ Flutter และ Firebase AI Logic
- ผสานรวมแพ็กเกจ
genuiเพื่อสร้างแพลตฟอร์มที่ขับเคลื่อนด้วย AI - เพิ่มแถบความคืบหน้าเพื่อระบุเมื่อแอปกำลังรอการตอบกลับจากตัวแทน
- สร้างแพลตฟอร์มที่มีชื่อและแสดงในจุดเฉพาะใน UI
- สร้างคอมโพเนนต์แคตตาล็อก GenUI ที่กำหนดเองซึ่งช่วยให้คุณควบคุมวิธีนำเสนองานได้
สิ่งที่คุณต้องมี
- เว็บเบราว์เซอร์ เช่น Chrome
- Flutter SDK ที่ติดตั้งไว้ในเครื่อง
- ติดตั้งและกำหนดค่า Firebase CLI แล้ว
Codelab นี้มีไว้สำหรับนักพัฒนาแอป Flutter ระดับกลาง
2. ก่อนเริ่มต้น
ตั้งค่าโปรเจ็กต์ Flutter
- หากยังไม่ได้ติดตั้ง ให้ติดตั้ง Flutter SDK ในเครื่อง
- เปิดเทอร์มินัลและเรียกใช้
flutter createเพื่อสร้างโปรเจ็กต์ใหม่flutter create intro_to_genui cd intro_to_genui - เพิ่มทรัพยากร Dependency ที่จำเป็นลงในโปรเจ็กต์ Flutter ดังนี้
ส่วนflutter pub add firebase_core firebase_ai genui json_schema_builderdependenciesสุดท้ายควรมีลักษณะดังนี้ (หมายเลขเวอร์ชันอาจแตกต่างกันเล็กน้อย)dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.9 firebase_core: ^4.15.0 firebase_ai: ^4.0.0 genui: ^0.10.3 json_schema_builder: ^0.1.7 - เรียกใช้
flutter pub getเพื่อดาวน์โหลดแพ็กเกจทั้งหมด หากระบบแจ้งว่ามีแพ็กเกจเวอร์ชันใหม่กว่า คุณสามารถเรียกใช้flutter pub outdatedเพื่อตรวจสอบเวอร์ชันและflutter pub upgradeเพื่ออัปเดตการอ้างอิงได้
ตั้งค่าโปรเจ็กต์ Firebase
- ติดตั้ง Firebase CLI หากยังไม่ได้ติดตั้ง
- เข้าสู่ระบบ Firebase โดยใช้บัญชี Google โดยทำดังนี้
firebase login - ติดตั้ง FlutterFire CLI โดยทำดังนี้
dart pub global activate flutterfire_cli - จากไดเรกทอรีโปรเจ็กต์ Flutter ให้เรียกใช้คำสั่งต่อไปนี้เพื่อกำหนดค่าโปรเจ็กต์ Flutter ให้ใช้ Firebase
คำสั่งนี้จะดำเนินการต่อไปนี้flutterfire configure- ถามว่าคุณต้องการใช้โปรเจ็กต์ Firebase ที่มีอยู่หรือสร้างโปรเจ็กต์ Firebase ใหม่ เลือกสร้างโปรเจ็กต์ Firebase ใหม่
- ระบบจะถามว่าคุณต้องการกำหนดเป้าหมายแพลตฟอร์มใด (iOS, Android, เว็บ) สำหรับแอป Flutter ในตอนนี้ ให้เลือกเว็บ
คำสั่ง flutterfire configure จะสร้างโปรเจ็กต์ Firebase และเว็บแอป Firebase ใหม่ในโปรเจ็กต์ Firebase นั้นโดยอัตโนมัติ จากนั้นคำสั่งจะสร้างไฟล์กำหนดค่า Firebase (firebase_options.dart) และเพิ่มลงในไดเรกทอรี lib/ ของโปรเจ็กต์ Flutter โดยอัตโนมัติ
โปรดทราบว่าแอปสำหรับ Codelab นี้จะทำงานได้เมื่อติดตั้ง Flutter SDK และ Chrome ไว้ในเครื่องเท่านั้น (กล่าวคือ แอปจะสร้างเป็นเว็บแอป) แต่เนื่องจากแอปนี้สร้างขึ้นด้วย Flutter จึงใช้งานได้บนแพลตฟอร์มอื่นๆ ด้วย ดังนั้นเมื่อสิ้นสุด Codelab ให้ลองเรียกใช้ flutterfire configure อีกครั้งเพื่อเพิ่มการรองรับ iOS, Android หรือแพลตฟอร์มอื่น แล้วสร้างแอปใหม่ในแพลตฟอร์มนั้น
ดูข้อมูลเพิ่มเติมได้ที่วิธีการเพิ่ม Firebase ลงในแอป Flutter
ตั้งค่า Firebase AI Logic
- ลงชื่อเข้าใช้คอนโซล Firebase ใช้บัญชี Google เดียวกับที่คุณใช้เข้าสู่ระบบ Firebase CLI
- เลือกโปรเจ็กต์ Firebase ที่คุณเพิ่งสร้างโดยใช้ FlutterFire CLI
- จากเมนูการนำทางด้านซ้าย ให้เลือกบริการ AI > ตรรกะ AI
- คลิกเริ่มต้นใช้งานเพื่อเปิดเวิร์กโฟลว์แบบมีคำแนะนำ
- เลือกเริ่มต้นด้วย Gemini Developer API แล้วทำตามข้อความแจ้งบนหน้าจอเพื่อตั้งค่า Firebase AI Logic
คุณมีปลั๊กอิน FlutterFire ที่จำเป็นสำหรับการใช้ Firebase AI Logic จากส่วน "ตั้งค่าโปรเจ็กต์ Flutter" อยู่แล้ว คุณพร้อมที่จะเริ่มเขียนโค้ดแอปในขั้นตอนถัดไปแล้ว
3. สร้างโครงสร้างอินเทอร์เฟซแชทพื้นฐาน
ก่อนที่จะเปิดตัว Generative UI แอปของคุณต้องมีรากฐาน ซึ่งก็คือแอปพลิเคชันแชทแบบข้อความพื้นฐานที่ขับเคลื่อนโดย Firebase AI Logic หากต้องการเริ่มต้นใช้งานอย่างรวดเร็ว ให้คัดลอกและวางการตั้งค่าทั้งหมดสำหรับอินเทอร์เฟซแชท

สร้างวิดเจ็ตบับเบิลข้อความ
หากต้องการแสดง SMS จากผู้ใช้และตัวแทน แอปของคุณต้องมีวิดเจ็ต สร้างไฟล์ใหม่ชื่อ lib/message_bubble.dart แล้วเพิ่มคลาสต่อไปนี้
import 'package:flutter/material.dart';
class MessageBubble extends StatelessWidget {
final String text;
final bool isUser;
const MessageBubble({super.key, required this.text, required this.isUser});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final bubbleColor = isUser
? colorScheme.primary
: colorScheme.surfaceContainerHighest;
final textColor = isUser
? colorScheme.onPrimary
: colorScheme.onSurfaceVariant;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6.0, horizontal: 8.0),
child: Column(
crossAxisAlignment: isUser
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: isUser
? MainAxisAlignment.end
: MainAxisAlignment.start,
children: [
Flexible(
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 12.0,
),
decoration: BoxDecoration(
color: bubbleColor,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(20),
topRight: const Radius.circular(20),
bottomLeft: Radius.circular(isUser ? 20 : 0),
bottomRight: Radius.circular(isUser ? 0 : 20),
),
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(20),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
gradient: isUser
? LinearGradient(
colors: [
colorScheme.primary,
colorScheme.primary.withAlpha(200),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
)
: null,
),
child: Text(
text,
style: theme.textTheme.bodyLarge?.copyWith(
color: textColor,
height: 1.3,
),
),
),
),
],
),
const SizedBox(height: 2),
],
),
);
}
}
MessageBubble คือ StatelessWidget ที่แสดงข้อความแชทเดียว ซึ่งจะใช้ในภายหลังใน Codelab นี้เพื่อแสดงข้อความจากทั้งคุณและตัวแทน แต่ส่วนใหญ่จะเป็นเพียงวิดเจ็ต Text ที่สวยงาม
ใช้ UI ของ Chat ใน main.dart
แทนที่เนื้อหาทั้งหมดของ lib/main.dart ด้วยการติดตั้งใช้งานแชทบ็อตแบบข้อความที่สมบูรณ์ต่อไปนี้
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ai/firebase_ai.dart';
import 'package:intro_to_genui/message_bubble.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Just Today',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
sealed class ConversationItem {}
class TextItem extends ConversationItem {
final String text;
final bool isUser;
TextItem({required this.text, this.isUser = false});
}
class _MyHomePageState extends State<MyHomePage> {
final List<ConversationItem> _items = [];
final _textController = TextEditingController();
final _scrollController = ScrollController();
late final ChatSession _chatSession;
@override
void initState() {
super.initState();
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-3.5-flash',
);
_chatSession = model.startChat();
_chatSession.sendMessage(Content.text(systemInstruction));
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
});
}
@override
void dispose() {
_textController.dispose();
_scrollController.dispose();
super.dispose();
}
Future<void> _addMessage() async {
final text = _textController.text;
if (text.trim().isEmpty) {
return;
}
_textController.clear();
setState(() {
_items.add(TextItem(text: text, isUser: true));
});
_scrollToBottom();
final response = await _chatSession.sendMessage(Content.text(text));
if (response.text?.isNotEmpty ?? false) {
setState(() {
_items.add(TextItem(text: response.text!, isUser: false));
});
_scrollToBottom();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('Just Today'),
),
body: Column(
children: [
Expanded(
child: ListView(
controller: _scrollController,
padding: const EdgeInsets.all(16),
children: [
for (final item in _items)
switch (item) {
TextItem() => MessageBubble(
text: item.text,
isUser: item.isUser,
),
},
],
),
),
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: _textController,
onSubmitted: (_) => _addMessage(),
decoration: const InputDecoration(
hintText: 'Enter a message',
),
),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: _addMessage,
child: const Text('Send'),
),
],
),
),
),
],
),
);
}
}
const systemInstruction = '''
## PERSONA
You are an expert task planner.
## GOAL
Work with me to produce a list of tasks that I should do today, and then track
the completion status of each one.
## RULES
Talk with me only about tasks that I should do today.
Do not engage in conversation about any other topic.
Do not offer suggestions unless I ask for them.
Do not offer encouragement unless I ask for it.
Do not offer advice unless I ask for it.
Do not offer opinions unless I ask for them.
## PROCESS
### Planning
* Ask me for information about tasks that I should do today.
* Synthesize a list of tasks from that information.
* Ask clarifying questions if you need to.
* When you have a list of tasks that you think I should do today, present it
to me for review.
* Respond to my suggestions for changes, if I have any, until I accept the
list.
### Tracking
* Once the list is accepted, ask me to let you know when individual tasks are
complete.
* If I tell you a task is complete, mark it as complete.
* Once all tasks are complete, send a message acknowledging that, and then
end the conversation.
''';
ไฟล์ main.dart ที่คุณเพิ่งคัดลอกและวางจะตั้งค่า ChatSession พื้นฐานโดยใช้ Firebase AI Logic และพรอมต์ใน systemInstruction โดยจะจัดการเทิร์นการสนทนาด้วยการเก็บรักษารายการองค์ประกอบ TextItem และแสดงองค์ประกอบเหล่านั้นควบคู่ไปกับคำค้นหาของผู้ใช้โดยใช้วิดเจ็ต MessageBubble ที่คุณสร้างไว้ก่อนหน้านี้
โปรดตรวจสอบสิ่งต่อไปนี้ก่อนดำเนินการต่อ
- เมธอด
initStateคือตำแหน่งที่ตั้งค่าการเชื่อมต่อกับ Firebase AI Logic - แอปมี
TextFieldและปุ่มสำหรับส่งข้อความไปยังตัวแทน - เมธอด
_addMessageคือตำแหน่งที่ระบบจะส่งข้อความของผู้ใช้ไปยัง Agent - รายการ
_itemsคือที่เก็บประวัติการสนทนา - ข้อความจะแสดงใน
ListViewโดยใช้วิดเจ็ตMessageBubble
ทดสอบแอป
เมื่อมีโค้ดแล้ว คุณก็จะเรียกใช้และทดสอบแอปได้
flutter run -d chrome
ลองแชทกับ Agent เกี่ยวกับงานบางอย่างที่คุณต้องการทำให้เสร็จในวันนี้ แม้ว่า UI ที่เป็นข้อความอย่างเดียวจะทำงานได้ แต่ GenUI จะช่วยให้ประสบการณ์การใช้งานง่ายขึ้นและเร็วขึ้น
หลังจากทดสอบเสร็จแล้ว ให้หยุดแอปที่กำลังทำงานโดยกด q (หรือ Ctrl+C) ในเทอร์มินัลก่อนดำเนินการต่อในขั้นตอนถัดไป
4. ผสานรวมแพ็กเกจ GenUI
ตอนนี้ถึงเวลาอัปเกรดจากข้อความธรรมดาเป็น Generative UI แล้ว คุณจะเปลี่ยนลูปการรับส่งข้อความ Firebase พื้นฐานเป็นออบเจ็กต์ GenUI Conversation, Catalog และ SurfaceController ซึ่งจะช่วยให้โมเดล AI สร้างอินสแตนซ์วิดเจ็ต Flutter จริงภายในสตรีมแชทได้

แพ็กเกจ genui มีคลาส 5 คลาสที่คุณจะใช้ตลอด Codelab นี้ ได้แก่
SurfaceControllerแมป UI ที่โมเดลสร้างขึ้นกับหน้าจอA2uiTransportAdapterเชื่อมต่อคำขอ GenUI ภายในกับโมเดลภาษาภายนอกConversationจะรวมตัวควบคุมและอะแดปเตอร์การรับส่งข้อมูลไว้ด้วย API แบบรวมรายการเดียวสำหรับแอป FlutterCatalogอธิบายวิดเจ็ตและพร็อพเพอร์ตี้ที่พร้อมใช้งานสำหรับโมเดลภาษาSurfaceเป็นวิดเจ็ตที่แสดง UI ที่โมเดลสร้างขึ้น
เตรียมพร้อมที่จะแสดง Surface ที่สร้างขึ้น
ใน lib/main.dart โค้ดที่มีอยู่จะมีคลาส TextItem ที่แสดงถึงข้อความเดียวในการสนทนา เพิ่มคลาส SurfaceItem ต่อจากคลาส TextItem ทันทีเพื่อแสดงถึง Surface ที่สร้างโดย Agent ดังนี้
class TextItem extends ConversationItem {
// ... existing code ...
}
// New!
class SurfaceItem extends ConversationItem {
final String surfaceId;
SurfaceItem({required this.surfaceId});
}
เริ่มต้นองค์ประกอบที่ใช้สร้างสรรค์ GenUI
ที่ด้านบนของ lib/main.dart ให้นำเข้าไลบรารี genui ดังนี้
import 'package:genui/genui.dart' hide TextPart;
import 'package:genui/genui.dart' as genui;
ทั้งแพ็กเกจ genui และแพ็กเกจ firebase_ai มีคลาส TextPart การนำเข้า genui ด้วยวิธีนี้จะทำให้คุณกำหนดเนมสเปซของ TextPart เวอร์ชันดังกล่าวเป็น genui.TextPart เพื่อหลีกเลี่ยงการชนกันของชื่อ
ประกาศตัวควบคุมฟังก์ชันหลักใน _MyHomePageState หลังจาก _chatSession:
class _MyHomePageState extends State<MyHomePage> {
// ... existing members
late final ChatSession _chatSession;
// Add GenUI controllers
late final SurfaceController _controller;
late final A2uiTransportAdapter _transport;
late final Conversation _conversation;
late final Catalog catalog;
ถัดไป ให้อัปเดต initState เพื่อเตรียมตัวควบคุมของไลบรารี GenUI
นำบรรทัดนี้ออกจาก initState
_chatSession.sendMessage(Content.text(systemInstruction));
จากนั้นเพิ่มโค้ดต่อไปนี้
@override
void initState() {
// ... existing code ...
// Initialize the GenUI Catalog.
// The genui package provides a default set of primitive widgets (like text
// and basic buttons) out of the box using this class.
catalog = BasicCatalogItems.asCatalog();
// Create a SurfaceController to manage the state of generated surfaces.
_controller = SurfaceController(catalogs: [catalog]);
// Create a transport adapter that will process messages to and from the
// agent, looking for A2UI messages.
_transport = A2uiTransportAdapter(onSend: _sendAndReceive);
// Link the transport and SurfaceController together in a Conversation,
// which provides your app a unified API for interacting with the agent.
_conversation = Conversation(
controller: _controller,
transport: _transport,
);
}
โค้ดนี้จะสร้างฟาซาด Conversation ที่จัดการตัวควบคุมและอะแดปเตอร์ การสนทนานั้นจะให้สตรีมเหตุการณ์แก่แอปของคุณ ซึ่งแอปสามารถใช้เพื่อติดตามสิ่งที่ Agent กำลังสร้าง รวมถึงวิธีการส่งข้อความไปยัง Agent
จากนั้นให้สร้าง Listener สำหรับเหตุการณ์การสนทนา ซึ่งรวมถึงเหตุการณ์ที่เกี่ยวข้องกับพื้นผิว ตลอดจนเหตุการณ์สำหรับข้อความและข้อผิดพลาด
@override
void initState() {
// ... existing code ...
// Listen to GenUI stream events to update the UI
_conversation.events.listen((event) {
setState(() {
switch (event) {
case ConversationSurfaceAdded added:
_items.add(SurfaceItem(surfaceId: added.surfaceId));
_scrollToBottom();
case ConversationSurfaceRemoved removed:
_items.removeWhere(
(item) =>
item is SurfaceItem && item.surfaceId == removed.surfaceId,
);
case ConversationContentReceived content:
_items.add(TextItem(text: content.text, isUser: false));
_scrollToBottom();
case ConversationError error:
debugPrint('GenUI Error: ${error.error}');
default:
}
});
});
}
สุดท้าย ให้สร้างพรอมต์ของระบบและส่งไปยัง Agent ดังนี้
@override
void initState() {
// ... existing code ...
// Create the system prompt for the agent, which will include this app's
// system instruction as well as the schema for the catalog.
final promptBuilder = PromptBuilder.chat(
catalog: catalog,
systemPromptFragments: [systemInstruction],
);
// Send the prompt into the Conversation, which will subsequently route it
// to Firebase using the transport mechanism.
_conversation.sendRequest(
ChatMessage.system(promptBuilder.systemPromptJoined()),
);
}
นอกจากนี้ ให้อัปเดตdispose()เมธอดใน _MyHomePageState เพื่อให้ระบบล้างข้อมูลคอนโทรลเลอร์ GenUI ที่เพิ่มใหม่ได้อย่างถูกต้องเมื่อทิ้งวิดเจ็ต
@override
void dispose() {
_conversation.dispose();
_transport.dispose();
_controller.dispose();
_textController.dispose();
_scrollController.dispose();
super.dispose();
}
แพลตฟอร์ม Display
จากนั้นอัปเดตเมธอด build ของ ListView เพื่อแสดง SurfaceItem ในรายการ _items ดังนี้
Expanded(
child: ListView(
controller: _scrollController,
padding: const EdgeInsets.all(16),
children: [
for (final item in _items)
switch (item) {
TextItem() => MessageBubble(
text: item.text,
isUser: item.isUser,
),
// New!
SurfaceItem() => Surface(
surfaceContext: _controller.contextFor(
item.surfaceId,
),
),
},
],
),
),
ตัวสร้างสำหรับวิดเจ็ต Surface จะใช้ surfaceContext ที่บอกว่ามีหน้าที่รับผิดชอบในการแสดงผลแพลตฟอร์มใด SurfaceController ที่สร้างไว้ก่อนหน้านี้ _controller จะให้คำจำกัดความและสถานะสำหรับแต่ละพื้นผิว และตรวจสอบว่ามีการสร้างใหม่เมื่อมีการอัปเดต
เชื่อมต่อ GenUI กับ Firebase AI Logic
แพ็กเกจ genui ใช้แนวทาง "นำโมเดลของคุณมาเอง" ซึ่งหมายความว่าคุณสามารถควบคุมได้ว่าจะใช้ LLM ใดในการขับเคลื่อนประสบการณ์การใช้งานของคุณ ในกรณีนี้ คุณกำลังใช้ Firebase AI Logic แต่แพ็กเกจนี้สร้างขึ้นเพื่อทำงานร่วมกับ Agent และผู้ให้บริการที่หลากหลาย
อิสระดังกล่าวทำให้คุณต้องรับผิดชอบเพิ่มขึ้นเล็กน้อย กล่าวคือ คุณต้องนำข้อความที่สร้างโดยแพ็กเกจ genui และส่งไปยัง Agent ที่เลือก และคุณต้องนำคำตอบของ Agent และส่งกลับไปยัง genui
โดยคุณจะต้องกำหนดเมธอด _sendAndReceive ที่อ้างอิงในโค้ดสำหรับขั้นตอนก่อนหน้า ใน lib/main.dart ให้เพิ่ม _sendAndReceive ภายในคลาส _MyHomePageState (เช่น หลังบรรทัด late final Catalog catalog; ทันที)
class _MyHomePageState extends State<MyHomePage> {
// ... existing code ...
late final Catalog catalog;
// New!
Future<void> _sendAndReceive(ChatMessage msg) async {
final buffer = StringBuffer();
// Reconstruct the message part fragments
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 text = buffer.toString();
// Send the string to Firebase AI Logic.
final response = await _chatSession.sendMessage(Content.text(text));
if (response.text?.isNotEmpty ?? false) {
// Feed the response back into GenUI's transportation layer
_transport.addChunk(response.text!);
}
}
แพ็กเกจ genui จะเรียกใช้เมธอดนี้เมื่อใดก็ตามที่ต้องการส่งข้อความไปยังตัวแทน การเรียกใช้ addChunk ที่ส่วนท้ายของเมธอดจะส่งคำตอบของ Agent กลับไปยังแพ็กเกจ genui ซึ่งจะช่วยให้แพ็กเกจประมวลผลคำตอบและสร้าง UI ได้
สุดท้าย ให้แทนที่เมธอด _addMessage ที่มีอยู่ทั้งหมดด้วยเวอร์ชันใหม่นี้ เพื่อให้ระบบกำหนดเส้นทางข้อความไปยัง Conversation แทนที่จะเป็น Firebase โดยตรง
Future<void> _addMessage() async {
final text = _textController.text;
if (text.trim().isEmpty) {
return;
}
_textController.clear();
setState(() {
_items.add(TextItem(text: text, isUser: true));
});
_scrollToBottom();
// Send the user's input through GenUI instead of directly to Firebase.
await _conversation.sendRequest(ChatMessage.user(text));
}
เท่านี้ก็เรียบร้อย ลองเรียกใช้แอปอีกครั้ง นอกจากข้อความแล้ว คุณจะเห็นเอเจนต์สร้างพื้นผิว UI เช่น ปุ่ม วิดเจ็ตข้อความ และอื่นๆ
คุณยังลองขอให้ Agent แสดง UI ในลักษณะที่เฉพาะเจาะจงได้ด้วย เช่น ลองใช้ข้อความอย่าง "แสดงงานของฉันในคอลัมน์ โดยมีปุ่มทำเครื่องหมายแต่ละงานว่าเสร็จแล้ว"
5. เพิ่มสถานะรอ
การสร้าง LLM เป็นแบบอะซิงโครนัส ขณะรอการตอบกลับ อินเทอร์เฟซแชทจะต้องปิดใช้ปุ่มป้อนข้อมูลและแสดงสัญญาณบอกสถานะความคืบหน้าเพื่อให้ผู้ใช้ทราบว่า GenUI กำลังสร้างเนื้อหา โชคดีที่genuiแพ็กเกจมีListenableที่คุณใช้ติดตามสถานะของการสนทนาได้ ค่า ConversationState นั้นมีพร็อพเพอร์ตี้ isWaiting เพื่อพิจารณาว่าโมเดลกำลังสร้างเนื้อหาหรือไม่
ห่อหุ้มตัวควบคุมอินพุตด้วย ValueListenableBuilder
ในเมธอด build ของ _MyHomePageState ใน lib/main.dart ให้ค้นหาวิดเจ็ต SafeArea ที่ด้านล่างของ Column และรวม Row ย่อย (ซึ่งมี TextField และ ElevatedButton) ด้วย ValueListenableBuilder ที่คอยฟัง _conversation.state เมื่อตรวจสอบ state.isWaiting คุณจะปิดใช้อินพุตขณะที่โมเดลกำลังสร้างเนื้อหาได้ โดยทำดังนี้
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
// Wrap the Row in a ValueListenableBuilder:
child: ValueListenableBuilder<ConversationState>(
valueListenable: _conversation.state,
builder: (context, state, child) {
return Row(
children: [
Expanded(
child: TextField(
controller: _textController,
// Also disable the Enter key submission when waiting!
onSubmitted: state.isWaiting ? null : (_) => _addMessage(),
decoration: const InputDecoration(
hintText: 'Enter a message',
),
),
),
const SizedBox(width: 8),
ElevatedButton(
// Disable the send button when the model is generating
onPressed: state.isWaiting ? null : _addMessage,
child: const Text('Send'),
),
],
);
},
),
),
),
เพิ่มแถบความคืบหน้า
ในเมธอด build ของ _MyHomePageState ให้รวมวิดเจ็ต Column หลักไว้ใน Stack และเพิ่ม ValueListenableBuilder ที่แสดงผล LinearProgressIndicator เป็นบุตรหลานลำดับที่ 2 ของ Stack นั้น เมื่อเสร็จแล้ว body ของ Scaffold ควรมีลักษณะดังนี้
body: Stack( // New!
children: [
Column(
children: [
// ... existing Expanded and SafeArea widgets ...
],
),
// Listen to the state again, this time to render a progress indicator
ValueListenableBuilder<ConversationState>(
valueListenable: _conversation.state,
builder: (context, state, child) {
if (state.isWaiting) {
return const LinearProgressIndicator();
}
return const SizedBox.shrink();
},
),
],
),
6. คงพื้นผิว GenUI ไว้
ที่ผ่านมา ระบบจะแสดงรายการงานในสตรีมแชทแบบเลื่อน โดยจะเพิ่มข้อความหรือแพลตฟอร์มใหม่ๆ ลงในรายการเมื่อมาถึง ในขั้นตอนถัดไป คุณจะเห็นวิธีตั้งชื่อพื้นผิวและแสดงในตำแหน่งที่เฉพาะเจาะจงภายใน UI
ก่อนอื่น ที่ด้านบนของ lib/main.dart ก่อน void main() ให้ประกาศค่าคงที่ที่จะใช้เป็นรหัสพื้นผิว ดังนี้
const taskDisplaySurfaceId = 'task_display';
ประการที่ 2 ใน initState() ให้อัปเดตคำสั่ง switch ในเครื่องมือฟัง Conversation เพื่อให้แน่ใจว่าระบบจะไม่เพิ่มพื้นผิวที่มีรหัสดังกล่าวลงใน _items หากต้องการดำเนินการนี้ ให้อัปเดตสาขา case ConversationSurfaceAdded added: ภายใน _conversation.events.listen โดยการรวมบรรทัด _items.add(...) และ _scrollToBottom() ไว้ภายในคำสั่ง if ดังนี้
_conversation.events.listen((event) {
setState(() {
switch (event) {
case ConversationSurfaceAdded added:
// Wrap these two lines in an if check:
if (added.surfaceId != taskDisplaySurfaceId) {
_items.add(SurfaceItem(surfaceId: added.surfaceId));
_scrollToBottom();
}
case ConversationSurfaceRemoved removed:
// ... existing code ...
จากนั้นเปิดโครงสร้างเลย์เอาต์ของแผนผังวิดเจ็ตใน _MyHomePageState.build เพื่อสร้างพื้นที่สำหรับพื้นผิวที่ปักหมุดไว้ก่อนบันทึกการแชททันที แทรก AnimatedSize และ const Divider() เป็นแท็กย่อย 2 แท็กแรกของ Column หลัก โดยแทรกไว้ก่อนโค้ด Expanded(child: ListView(...)) ดังนี้
body: Stack(
children: [
Column(
children: [
// Insert these two new widgets at the top of the Column:
AnimatedSize(
duration: const Duration(milliseconds: 300),
child: Container(
padding: const EdgeInsets.all(16),
alignment: Alignment.topLeft,
child: Surface(
surfaceContext: _controller.contextFor(
taskDisplaySurfaceId,
),
),
),
),
const Divider(),
Expanded(
child: ListView(
// ... existing code ...
จนถึงตอนนี้ Agent ของคุณมีอิสระในการสร้างและใช้แพลตฟอร์มตามที่เห็นสมควร หากต้องการให้คำสั่งที่เฉพาะเจาะจงมากขึ้น คุณต้องกลับไปที่พรอมต์ของระบบ เพิ่มส่วน ## USER INTERFACE ต่อไปนี้ที่ส่วนท้ายของพรอมต์ที่จัดเก็บไว้ในค่าคงที่ systemInstruction
const systemInstruction = '''
// ... existing prompt content ...
## USER INTERFACE
* To display the list of tasks create one and only one instance of the
TaskDisplay catalog item. Use "$taskDisplaySurfaceId" as its surface ID.
* Update $taskDisplaySurfaceId as necessary when the list changes.
* $taskDisplaySurfaceId must include a button for each task that I can use
to mark it complete. When I use that button to mark a task complete, it
should send you a message indicating what I've done.
* Avoid repeating the same information in a single message.
* When responding with text, rather than A2UI messages, be brief.
''';
คุณต้องให้วิธีการที่ชัดเจนแก่ Agent เกี่ยวกับเวลาและวิธีใช้แพลตฟอร์ม UI การบอกให้เอเจนต์ใช้แคตตาล็อกไอเทมและรหัสพื้นผิวที่เฉพาะเจาะจง (และใช้ซ้ำอินสแตนซ์เดียว) จะช่วยให้มั่นใจได้ว่าเอเจนต์จะสร้างอินเทอร์เฟซที่คุณต้องการเห็น
เรายังต้องดำเนินการอีกมาก แต่คุณลองเรียกใช้แอปอีกครั้งเพื่อดูว่าเอเจนต์สร้างพื้นผิวการแสดงงานที่ด้านบนของ UI หรือไม่
7. สร้างวิดเจ็ตแคตตาล็อกที่กำหนดเอง
ซึ่งในขณะนี้ยังไม่มีรายการแคตตาล็อก TaskDisplay ในขั้นตอนถัดไป คุณจะแก้ไขปัญหานี้โดยสร้างสคีมาข้อมูล, คลาสเพื่อแยกวิเคราะห์สคีมานั้น, วิดเจ็ต และรายการแคตตาล็อกที่รวมทุกอย่างเข้าด้วยกัน
ก่อนอื่น ให้สร้างไฟล์ใหม่ชื่อ task_display.dart ในไดเรกทอรี lib/ ของโปรเจ็กต์ แล้วเพิ่มการนําเข้าต่อไปนี้
import 'package:flutter/material.dart';
import 'package:genui/genui.dart';
import 'package:json_schema_builder/json_schema_builder.dart';
สร้างสคีมาข้อมูล
ถัดไป ให้กำหนดสคีมาข้อมูลที่ Agent จะระบุเมื่อต้องการสร้างการแสดงผลงาน กระบวนการนี้ใช้ตัวสร้างที่ซับซ้อนบางอย่างจากแพ็กเกจ json_schema_builder แต่โดยพื้นฐานแล้วคุณเพียงแค่กำหนดสคีมา JSON ที่ใช้ในข้อความที่ส่งไปยังและจากเอเจนต์
เริ่มต้นด้วย S.object พื้นฐานที่อ้างอิงชื่อคอมโพเนนต์ ดังนี้
final taskDisplaySchema = S.object(
properties: {
'component': S.string(enumValues: ['TaskDisplay']),
},
);
จากนั้นเพิ่ม title, tasks, name, isCompleted และ completeAction ลงในพร็อพเพอร์ตี้สคีมา
final taskDisplaySchema = S.object(
properties: {
'component': S.string(enumValues: ['TaskDisplay']),
'title': S.string(description: 'The title of the task list'),
'tasks': S.list(
description: 'A list of tasks to be completed today',
items: S.object(
properties: {
'name': S.string(description: 'The name of the task to be completed'),
'isCompleted': S.boolean(
description: 'Whether the task is completed',
),
'completeAction': A2uiSchemas.action(
description:
'The action performed when the user has completed the task.',
),
},
),
),
},
);
ดูพร็อพเพอร์ตี้ completeAction โดยสร้างขึ้นด้วย A2uiSchemas.action ซึ่งเป็นตัวสร้างพร็อพเพอร์ตี้สคีมาที่แสดงถึงการดำเนินการ A2UI การเพิ่มการดำเนินการลงในสคีมาจะทำให้แอปบอก Agent ว่า "เมื่อคุณให้งานฉัน โปรดระบุชื่อและข้อมูลเมตาสำหรับการดำเนินการที่ฉันใช้เพื่อบอกคุณได้ว่างานนั้นเสร็จสมบูรณ์แล้ว" หลังจากนั้น แอปจะเรียกใช้การดำเนินการดังกล่าวเมื่อผู้ใช้แตะช่องทำเครื่องหมาย
จากนั้นเพิ่มฟิลด์ required ลงในสคีมา ซึ่งจะสั่งให้ Agent ป้อนข้อมูลพร็อพเพอร์ตี้บางอย่างทุกครั้ง ในกรณีนี้ คุณต้องระบุพร็อพเพอร์ตี้ทุกรายการ
final taskDisplaySchema = S.object(
properties: {
'component': S.string(enumValues: ['TaskDisplay']),
'title': S.string(description: 'The title of the task list'),
'tasks': S.list(
description: 'A list of tasks to be completed today',
items: S.object(
properties: {
'name': S.string(description: 'The name of the task to be completed'),
'isCompleted': S.boolean(
description: 'Whether the task is completed',
),
'completeAction': A2uiSchemas.action(
description:
'The action performed when the user has completed the task.',
),
},
// New!
required: ['name', 'isCompleted', 'completeAction'],
),
),
},
// New!
required: ['title', 'tasks'],
);
สร้างคลาสการแยกวิเคราะห์ข้อมูล
เมื่อสร้างอินสแตนซ์ของคอมโพเนนต์นี้ ตัวแทนจะส่งข้อมูลที่ตรงกับสคีมา เพิ่ม 2 คลาสเพื่อแยกวิเคราะห์ JSON ขาเข้าเป็นออบเจ็กต์ Dart ที่มีการระบุประเภทอย่างชัดเจน สังเกตว่า _TaskDisplayData จัดการโครงสร้างรูทอย่างไรในขณะที่มอบหมายการแยกวิเคราะห์อาร์เรย์ด้านในให้ _TaskData
class _TaskData {
final String name;
final bool isCompleted;
final String actionName;
final JsonMap? actionContext;
_TaskData({
required this.name,
required this.isCompleted,
required this.actionName,
this.actionContext,
});
factory _TaskData.fromJson(Map<String, Object?> json) {
try {
final action = json['completeAction']! as JsonMap;
final event = action['event']! as JsonMap;
return _TaskData(
name: json['name'] as String,
isCompleted: json['isCompleted'] as bool,
actionName: event['name'] as String,
actionContext: event['context'] as JsonMap?,
);
} catch (e) {
throw Exception('Invalid JSON for _TaskData: $e');
}
}
}
class _TaskDisplayData {
final String title;
final List<_TaskData> tasks;
_TaskDisplayData({required this.title, required this.tasks});
factory _TaskDisplayData.fromJson(Map<String, Object?> json) {
try {
return _TaskDisplayData(
title: (json['title'] as String?) ?? 'Tasks',
tasks: (json['tasks'] as List<Object?>)
.map((e) => _TaskData.fromJson(e as Map<String, Object?>))
.toList(),
);
} catch (e) {
throw Exception('Invalid JSON for _TaskDisplayData: $e');
}
}
}
หากคุณเคยสร้างด้วย Flutter มาก่อน คลาสเหล่านี้อาจคล้ายกับคลาสที่คุณสร้างไว้ โดยจะยอมรับ JsonMap และแสดงผลออบเจ็กต์ที่มีประเภทชัดเจนซึ่งมีข้อมูลที่แยกวิเคราะห์จาก JSON
ดูช่อง actionName และ actionContext ใน _TaskData โดยจะดึงข้อมูลจากพร็อพเพอร์ตี้ completeAction ของ JSON และมีชื่อของการดำเนินการและบริบทข้อมูล (การอ้างอิงถึงตำแหน่งของการดำเนินการในโมเดลข้อมูลของ GenUI) โดยระบบจะใช้ข้อมูลเหล่านี้ในภายหลังเพื่อสร้าง UserActionEvent
โมเดลข้อมูลคือที่เก็บแบบรวมศูนย์ที่สังเกตได้สำหรับสถานะ UI แบบไดนามิกทั้งหมด ซึ่งดูแลโดยไลบรารี genui เมื่อ Agent สร้างคอมโพเนนต์ UI จากแคตตาล็อก Agent จะสร้างออบเจ็กต์ข้อมูลที่ตรงกับสคีมาของคอมโพเนนต์ด้วย ออบเจ็กต์ข้อมูลนี้จะจัดเก็บไว้ในโมเดลข้อมูลในไคลเอ็นต์ เพื่อให้สามารถใช้สร้างวิดเจ็ตและอ้างอิงในข้อความที่ส่งไปยัง Agent ในภายหลัง (เช่น completeAction ที่คุณกำลังจะเชื่อมต่อกับวิดเจ็ต)
เพิ่มวิดเจ็ต
ตอนนี้ให้สร้างวิดเจ็ตเพื่อแสดงรายการ โดยควรยอมรับอินสแตนซ์ของคลาส _TaskDisplayData และ Callback ที่จะเรียกใช้เมื่อดำเนินการเสร็จสมบูรณ์
class _TaskDisplay extends StatelessWidget {
final _TaskDisplayData data;
final void Function(_TaskData) onCompleteTask;
const _TaskDisplay({required this.data, required this.onCompleteTask});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
data.title,
style: Theme.of(context).textTheme.titleLarge,
),
),
...data.tasks.map(
(task) => CheckboxListTile(
title: Text(
task.name,
style: TextStyle(
decoration: task.isCompleted
? TextDecoration.lineThrough
: TextDecoration.none,
),
),
value: task.isCompleted,
onChanged: task.isCompleted
? null
: (val) {
if (val == true) {
onCompleteTask(task);
}
},
),
),
],
);
}
}
สร้าง CatalogItem
เมื่อสร้างสคีมา ตัวแยกวิเคราะห์ และวิดเจ็ตแล้ว ตอนนี้คุณก็สร้าง CatalogItem เพื่อเชื่อมโยงทั้งหมดเข้าด้วยกันได้
ที่ด้านล่างของ task_display.dart ให้สร้าง taskDisplay เป็นตัวแปรระดับบนสุด ใช้ _TaskDisplayData เพื่อแยกวิเคราะห์ JSON ที่เข้ามา และสร้างอินสแตนซ์ของวิดเจ็ต _TaskDisplay
final taskDisplay = CatalogItem(
name: 'TaskDisplay',
dataSchema: taskDisplaySchema,
widgetBuilder: (itemContext) {
final json = itemContext.data as Map<String, Object?>;
final data = _TaskDisplayData.fromJson(json);
return _TaskDisplay(
data: data,
onCompleteTask: (task) async {
// We will implement this next!
},
);
},
);
ใช้ onCompleteTask
วิดเจ็ตต้องสื่อสารกลับไปยังตัวแทนเมื่อดำเนินการเสร็จสิ้นเพื่อให้ทำงานได้ แทนที่ตัวยึดตำแหน่ง onCompleteTask ที่ว่างเปล่าด้วยโค้ดต่อไปนี้เพื่อสร้างและส่งเหตุการณ์โดยใช้ completeAction จากข้อมูลงาน
onCompleteTask: (task) async {
// A data context is a reference to a location in the data model. This line
// turns that reference into a concrete data object that the agent can use.
// It's kind of like taking a pointer and replacing it with the value it
// points to.
final JsonMap resolvedContext = await resolveContext(
itemContext.dataContext,
task.actionContext,
);
// Dispatch an event back to the agent, letting it know a task was completed.
// This will be sent to the agent in an A2UI message that includes the name
// of the action, the surface ID, and the resolved data context.
itemContext.dispatchEvent(
UserActionEvent(
name: task.actionName,
sourceComponentId: itemContext.id,
context: resolvedContext,
),
);
}
ลงทะเบียนรายการในแคตตาล็อก
สุดท้าย ให้เปิด main.dart นำเข้าไฟล์ใหม่ และลงทะเบียนไฟล์พร้อมกับรายการแคตตาล็อกอื่นๆ
เพิ่มการนำเข้านี้ที่ด้านบนของ lib/main.dart:
import 'task_display.dart';
แทนที่ catalog = BasicCatalogItems.asCatalog(); ในฟังก์ชัน initState() ด้วย
// The Catalog is immutable, so use copyWith to create a new version
// that includes our custom catalog item along with the basics.
catalog = BasicCatalogItems.asCatalog().copyWith(newItems: [taskDisplay]);
เท่านี้ก็เรียบร้อย รีสตาร์ทแอปแบบ Hot Restart เพื่อดูการเปลี่ยนแปลง
8. ทดลองใช้วิธีต่างๆ ในการโต้ตอบกับ Agent

ตอนนี้คุณได้เพิ่มวิดเจ็ตใหม่ลงในแคตตาล็อกและสร้างพื้นที่สำหรับวิดเจ็ตใน UI ของแอปแล้ว ก็ถึงเวลาสนุกกับการทำงานร่วมกับเอเจนต์ ประโยชน์หลักอย่างหนึ่งของ GenUI คือมีวิธีโต้ตอบกับข้อมูล 2 วิธี ได้แก่ ผ่าน UI ของแอปพลิเคชัน เช่น ปุ่มและช่องทำเครื่องหมาย และผ่าน Agent ที่เข้าใจภาษาธรรมชาติและสามารถให้เหตุผลเกี่ยวกับข้อมูลได้ ลองใช้ทั้ง 2 อย่างดู
- ใช้ช่องข้อความเพื่ออธิบายงาน 3 หรือ 4 รายการ แล้วดูงานเหล่านั้นปรากฏในรายการ
- ใช้ช่องทำเครื่องหมายเพื่อสลับสถานะของงานเป็นเสร็จแล้วหรือยังไม่เสร็จ
- สร้างรายการงาน 5-6 รายการ จากนั้นบอกให้ Agent นำงานที่ต้องขับรถไปทำออก
- บอกให้ Agent สร้างรายการงานที่ต้องทำซ้ำๆ เป็นรายการแยกกัน ("ฉันต้องซื้อการ์ดวันหยุดให้แม่ พ่อ และยาย สร้างงานแยกต่างหากสำหรับงานเหล่านั้น")
- บอกให้ Agent ทำเครื่องหมายงานทั้งหมดว่าเสร็จแล้วหรือยังไม่เสร็จ หรือให้ทำเครื่องหมายงาน 2-3 รายการแรกว่าเสร็จแล้ว
9. ขอแสดงความยินดี
ยินดีด้วย คุณได้สร้างแอปเครื่องมือติดตามงานที่ทำงานด้วยระบบ AI โดยใช้ Generative UI และ Flutter
สิ่งที่คุณได้เรียนรู้
- การโต้ตอบกับโมเดลพื้นฐานของ Google โดยใช้ Flutter Firebase SDK
- การแสดงผลอินเทอร์เฟซแบบอินเทอร์แอกทีฟที่ Gemini สร้างขึ้นโดยใช้ GenUI
- การปักหมุดพื้นผิวในเลย์เอาต์โดยใช้รหัสการแสดงผลแบบคงที่ที่กำหนดไว้ล่วงหน้า
- การออกแบบสคีมาที่กำหนดเองและแคตตาล็อกวิดเจ็ตสำหรับลูปการโต้ตอบที่แข็งแกร่ง