GenUI
Let the agent draw on your screen, with your widgets.
The agent can draw on your screen with your widgets. It sends a view as A2UI components, and you list the widgets it may use. Tandem tells the model what it can draw with and checks every view the model sends: a view reads only what the screen lists with ., and its buttons call only the methods listed with .. When the screen's data changes, the view updates on its own.
In this guide you take the order desk from the example and let the agent draw its summary with the desk's widgets.
You need a screen on TandemScope with its surface (quick start). Your coding agent draws through the bridge. An in-app agent draws with an AG-UI backend that puts the screen's context into the prompt (the agent backend), or with Firebase AI Logic. Use a strong remote model, such as Gemini. Project status lists the models that drew views in the release checks.
Give the agent your widgets
List the widgets the agent may draw with. A catalog belongs to one screen: its guidelines and example name that screen's data and methods. Another screen can use the same widgets in its own catalog, such as @TandemCatalog([., with its own guidelines and example. The order desk lists six, with a converter for its icons (Values the agent writes):
@TandemCatalog(
[DeskCard, DeskColumn, OrderLine, OrderTotal, DeskButton, CustomerCard],
converters: [DeskIconConverter()],
)
final class const DeskCatalog() with _$DeskCatalog;Run dart . Tandem reads the constructor of each widget. Its parameters are the properties the model can set:
| Parameter | The model writes |
|---|---|
Widget, Widget? | one component |
List<Widget> | components, or one component repeated for every item of a list in . |
VoidCallback, VoidCallback? | a method listed with . or ., with its arguments |
ValueChanged<T>, ValueChanged<T>? | a method listed with .; what the user enters fills one of its arguments |
Key, FocusNode, a controller | nothing; the widget keeps its default |
| any other type | a value, or a path into what . lists. Values the agent writes says which types Tandem reads |
A parameter of one of your own classes, such as Customer, is bound to a value the screen lists. The model never writes the object itself (An object from the screen). Flutter's Color, insets and alignment have a form Tandem ships. A type with no form keeps the widget's default when the parameter is optional; when it is required, the build stops and names the converter to add (Values the agent writes).
The widgets stay as they are. What the agent may read and call is decided in one place, the state class's agentCapabilities: onPressed can only call a method listed there, and a path can only point at a value listed there.
A callback the widget requires has to call something. When its method is not listed now, Tandem leaves the component out of the view. A nullable callback gets null.
No design system? List Flutter's own widgets, such as Column, Text, Card and FilledButton.
What you see: nothing yet. The agent has no place to draw.
Put a view on the screen
Put TandemView below TandemScope, where the view should appear. The order desk puts it below the form:
child: const SingleChildScrollView(
padding: .fromLTRB(12, 0, 12, 12),
child: TandemView(catalog: DeskCatalog()),
),TandemView takes no space until the agent draws, and it does not scroll. The desk wraps it in a scroll view, since the view can be taller than its place.
Run the app and ask the agent: "Show me the order."
The run offered the agent one more tool, tandem_show_view. The agent answered with a view that names your widgets. One line of it:
{"id": "line", "component": "OrderLine",
"name": {"path": "name"}, "quantity": {"path": "quantity"}, "lineTotal": {"path": "lineTotal"}}OrderLine is your widget's class name. name, quantity and lineTotal are its constructor parameters, each bound to a path into what . lists. Tandem checked every name and path before drawing.
In the tool call on the wire, components is a JSON array encoded as a string. The tool's schema and description tell the model that form. ScriptedAgent also accepts a list of components, as the test below shows.
While the agent draws, session. is Thinking(drawing: , so the screen can show that something is coming (session status).
Teach the model your components
The model knows your widgets only from what Tandem tells it. For each one, that is the first paragraph of the class's doc comment and its constructor. A widget without a doc comment stops the build, as a listed method without one does.
/// One line of the order: the product, how many, and the line total.
final class const OrderLine({
super.key,
required final String name,
required final int quantity,
required final String lineTotal,
final VoidCallback? onRemove,
final ValueChanged<int>? onQuantity,
}) extends StatelessWidget {
// …
}From this, the model reads one line:
- OrderLine: "name" (string), "quantity" (integer), "lineTotal" (string), "onRemove"? (action), "onQuantity"? (field: integer). One line of the order: the product, how many, and the line total.Write the comment for a reader who has never seen the screen: what the widget shows and when to use it. Name a parameter in the comment when its meaning is not obvious from its name.
The catalog's own doc comment gives the model its guidelines and one example view. The example is the components of a view, written for this screen. The build checks its component and property names against the catalog. In debug, TandemView reports paths and methods that do not fit the screen. Fix those diagnostics before sending the catalog to a model:
/// Start with a DeskCard. Show the customer as a CustomerCard, the order
/// lines as one OrderLine per item of /order/lines, then an OrderTotal of
/// /order, then a DeskButton for place_order when it is among your tools.
///
/// ```json
/// [
/// {"id": "root", "component": "DeskCard", "title": "Your order", "children": ["customer", "lines", "total", "place"]},
/// {"id": "customer", "component": "CustomerCard", "customer": {"path": "/order/customer"}},
/// {"id": "lines", "component": "DeskColumn", "children": {"componentId": "line", "path": "/order/lines"}},
/// {"id": "line", "component": "OrderLine", "name": {"path": "name"}, "quantity": {"path": "quantity"}, "lineTotal": {"path": "lineTotal"},
/// "onRemove": {"action": {"event": {"name": "set_quantity", "context": {"sku": {"path": "sku"}, "quantity": 0}}}},
/// "onQuantity": {"action": {"event": {"name": "set_quantity", "context": {"sku": {"path": "sku"}, "quantity": {"input": true}}}}}},
/// {"id": "total", "component": "OrderTotal", "order": {"path": "/order"}},
/// {"id": "place", "component": "DeskButton", "label": "Place order", "icon": "cart", "onPressed": {"action": {"event": {"name": "place_order"}}}}
/// ]
/// ```
@TandemCatalog(
[DeskCard, DeskColumn, OrderLine, OrderTotal, DeskButton, CustomerCard],
converters: [DeskIconConverter()],
)
final class const DeskCatalog() with _$DeskCatalog;Ask again: "Show me the order." The agent now picks OrderLine for a line and OrderTotal for the total, and it stops putting the total into plain text.
What you see: the same summary, with each component used for what the comment says.
Values the agent writes
A widget's parameter, a method's argument and a field of a value in . are the same thing to Tandem: a value with a Dart type. The type decides what the model may write. The first kind that fits decides:
| Kind | Dart | The model writes |
|---|---|---|
| converter | a type with a JsonConverter<T, : Tandem's for Color, insets and alignments, yours listed on the catalog or the agent | what S says, such as "#1E88E5" for a Color |
| scalar | String, int, double, num, bool | the value |
| text with a format | DateTime, Uri | "2026-11-02T10:00:00Z", "https:/ |
| enum | any enum, Flutter's TextAlign too | one of the names |
| token class | a class without a public constructor whose values are its own static members, such as your design system's text styles | one of the member names |
| nullable | T?; the parameter becomes optional | the value, or nothing |
| list | List<T>, Set<T> | an array |
| your own class | a public constructor and a getter for each parameter: DeskLine, a freezed class, a contract DTO | a path to a value the screen lists, never the object |
Tandem reads a class from its constructor and getters and never calls its toJson. Your backend may write an enum as 0; the model reads and writes its name.
Tandem's converter for Color takes #RRGGBB, or #RRGGBBAA with the opacity last, as in CSS. Each channel has 8 bits, in sRGB. Tandem also ships converters for EdgeInsets, EdgeInsetsDirectional and EdgeInsetsGeometry, and for Alignment, AlignmentDirectional and AlignmentGeometry. The directional ones keep the reading direction. A converter matches its type exactly, so a parameter of type EdgeInsets takes the converter of EdgeInsets, not the one of EdgeInsetsGeometry.
Not readable: a sealed class, Map, Duration, BigInt, Object and dynamic, functions, and types of Dart or Flutter outside the table, such as TextStyle and IconData. Your own class is readable, also when all its fields are numbers. A converter gives an unreadable type a form. It is JsonConverter<T, from json_annotation, the interface your DTOs may already use, and S is a type from the table. The desk's buttons take an icon, and the desk decides which icons the model may name:
/// An icon by name: cart, truck or receipt.
final class const DeskIconConverter()
implements JsonConverter<IconData, String> {
static const _icons = {
'cart': Icons.shopping_cart,
'truck': Icons.local_shipping,
'receipt': Icons.receipt_long,
};
@override
IconData fromJson(String json) =>
_icons[json] ??
(throw FormatException('Write one of ${_icons.keys.join(', ')}.'));
@override
String toJson(IconData object) =>
_icons.entries.firstWhere((e) => e.value == object).key;
}Tandem takes the schema from S and the description from the doc comment. When fromJson throws a FormatException, the model gets its message as a refusal with the property's path. Anything else it throws is reported as a bug of the app, and the value is refused. A converter you list for Color replaces Tandem's. A method or a value in . that needs a converter lists it on the agent, @TandemAgent(converters: . A design system exports its converters as a static list, and the app spreads it, as with components.
Two builds that give one type different converters, such as a design system's catalog and the app's agent, are a configuration error. The view reports it, and the run does not offer tandem_show_view. This holds in release too.
A required parameter of a type with no form stops the build and names the converter to add. If DeskButton. were required and the desk had no converter, the build would say: DeskButton. One widget of a spread design system stops the build of the app, on purpose: a widget the model cannot use is a mistake in the catalog, not a detail to warn about. An optional parameter of such a type keeps the widget's default, and the build says so in one line: DeskButton.
What you see: nothing new. The rule decides what the model may write in every view and every call.
An object from the screen
The order desk has a card for the customer. Its widget takes the whole Customer:
/// The customer the order is for, with their price list.
final class const CustomerCard({super.key, required final Customer customer})
extends StatelessWidget {
// …
}The model does not write a customer. It points at the one the screen lists:
{"id": "customer", "component": "CustomerCard", "customer": {"path": "/order/customer"}}Tandem hands the widget the Customer from order, the same object the form shows. An object in its place is refused: customer. A path to a value of another type is refused with the paths that fit. In a list template, {"path": is the item itself: a widget that takes a whole DeskLine reads "line": .
The desk's methods take plain values, setCustomer(String and setDelivery(String . A method can take an object of your own class instead, and then its parameter can mean two things. This sketch is not in the example:
/// Sets the customer the order is for; prices follow their price list.
void setCustomer(Customer customer) => …;
/// Sets where and when the order is delivered.
void setDelivery(@TandemInput() DeskDelivery delivery) => …;This setCustomer takes one of the customers the screen lists, say with .. The model points at it, {"customer": , and the method gets that Customer. setDelivery takes a delivery that does not exist yet. The model writes it, {"delivery": , and the tool's schema carries the fields of DeskDelivery, each read by the rule of the previous step.
Tandem cannot tell the two apart from the types: a Customer would be as easy to write as a DeskDelivery. A made-up customer is the mistake to prevent. A made-up delivery is what the method is for. So a parameter of your own class is a path, and @TandemInput() marks the one the model writes. A method that takes the fields instead, as the desk's setDelivery(String does, needs no mark.
A path is resolved against the data the agent read in this run. When that value has changed since, the call is refused: customer: With ., the request shows the arguments with each path replaced by its object as JSON. The approved method gets objects built from that JSON, so what the user approved is what runs. A change to what . lists invalidates the request, as for any approval.
A converter changes the object's form, not where it comes from. An app class read from its public unnamed constructor and getters still takes a path when it has a converter. @TandemInput() lets the agent write the converter's form instead.
What you see: the customer's card in the agent's view, the same customer as in the form.
Let the user act
The desk's widgets already have callbacks: OrderLine takes onRemove, DeskButton takes onPressed. In the catalog, a VoidCallback is a press, nullable or not. The model binds it to a method listed with . or . and gives the method its arguments. For the Remove button it writes:
{"id": "line", "component": "OrderLine",
"name": {"path": "name"}, "quantity": {"path": "quantity"}, "lineTotal": {"path": "lineTotal"},
"onRemove": {"action": {"event": {"name": "set_quantity", "context": {"sku": {"path": "sku"}, "quantity": 0}}}}}A press calls setQuantity the way the agent would, with the same validation and the same refusals. AgentCall and ApprovalRequest name the caller Caller.. Tandem checks the action before drawing: the method must be listed, and every argument must fit its parameter. place_order needs approval, so a DeskButton bound to it shows the approval card when pressed. Such a button is enabled only while the session is idle and the scope takes approvals. One action of a view runs at a time. While it runs, nullable action callbacks become null and required callbacks ignore further actions. The widget decides how that looks.
A component with a required action is left out when its method is no longer listed, its arguments are unavailable, or the scope cannot obtain its required approval. An action of an approval method cannot run when the scope has approvals: , and a field bound to an approval method never runs.
A press does not wake the agent. The method's answer goes into the notes the agent reads at its next run (notes from the app). When the agent should respond at once, wake it from onEvent:
/// Lets the agent answer once the user placed the order from its view.
void wakeOnPlacedOrder(
BuildContext context,
TandemEvent event,
TandemSession session,
) {
if (event case AgentCall(
tool: OrderDeskCubitTool.placeOrder,
caller: .view,
)) {
session.wake();
}
}The desk passes it to its scope as onEvent: .
A field is a press with a hole for what the user enters. OrderLine also takes ValueChanged<int>? , and the model binds it to set_quantity with {"input": where the value goes:
"onQuantity": {"action": {"event": {"name": "set_quantity", "context": {"sku": {"path": "sku"}, "quantity": {"input": true}}}}}The entry has the widget's type, here an int from the line's − and + buttons. Tandem checks before drawing that this type fits the parameter. A refusal of the method, such as Quantity , comes back as after a press. A field never writes into the screen's data: the quantity changes when setQuantity changes it, and the view follows. A field calls only a method listed with .. One bound to place_order is refused: line.
In the component's line, the model reads a press as (action) and a field as (field).
What you see: a Remove button and − and + on every line, and Place order with its approval card.
Keep the view honest
The view shows the screen's data by path, so it follows the screen. Change a quantity in the form: the line in the summary and the total change with it. On every change of the screen, Tandem copies what . lists into the view's data under the getter's name, /, and every bound property takes its new value. The widgets rebuild as they do anywhere else in Flutter.
The list of methods follows too. When the desk stops listing setQuantity, because the order was placed, the actions that call it get null. The Remove buttons go grey, and OrderLine hides its − and + buttons. The view stays, and only what it may do changes. A required property whose path has no value now, / before a customer is chosen, leaves its component out of the view until the value returns. An optional one keeps the widget's default.
Not everything in a view is a path. "title": is a literal, and a label needs one. The model is told to write screen data by path and to use a literal only for text the screen does not have. Tandem cannot tell a label from a copied value: a model that writes "lineTotal": shows a total that stops following the screen. Your catalog's guidelines and example keep the model on paths, so write every value from the screen as a path in both. A path the screen does not list is refused before anything is drawn; the next step shows the refusal.
What you see: change a quantity in the form and the summary follows. Place the order and the Remove buttons go grey.
When the agent gets it wrong
A view that does not match the screen is refused before anything is drawn. The refusal tells the model what to fix, one line per problem:
total.order: /order/sum is not in the data. Paths under /order: customer, lines, delivery, total.
line: OrderLine has no "price". Properties: name, quantity, lineTotal, onRemove, onQuantity.
place.onPressed: must call a method of the screen, as {"action": {"event": {"name": <method>, "context": {<parameter>: <value>}}}}. Methods: search_catalog, set_customer, set_quantity, set_delivery, place_order.The refusal is the result of tandem_show_view, so the model reads it in the same turn and sends a corrected view. The previous view stays on the screen meanwhile. After three refusals in a row, Tandem tells the model to answer in text and withholds tandem_show_view until the next message from the user or the app. Your backend's log has every refusal as a tool result.
A view is limited to 500 components, repeated list items included. When the screen's data grow past that, say a list of 600 orders, the view and its actions become unavailable and TandemView shows "This view is not available now." Draw your own with whenUnavailable, for example:
TandemView(
catalog: DeskCatalog(),
whenUnavailable: (context) => const Text('The summary is too large to show.'),
)The view returns on its own when the data fit again.
What you see: ask for "the order with a discount column". The first view is refused for a property OrderLine does not have, and the second one draws.
Test it without a model
ScriptedAgent from package:tandem/ draws the same view every time, so a widget test needs no backend. This script answers the first run with the catalog's own example, the components from its doc comment, and one sentence. setUp gives the desk a customer, two lines and a delivery:
setUp(() {
cubit =
OrderDeskCubit(
catalog: Catalog(products),
customers: Customers(customers),
orders: Orders(),
)
..setCustomer('acme')
..setQuantity('VC-HDMI-2M', 40)
..setQuantity('VM-27Q', 12)
..setDelivery('Magazynowa 5, 61-001 Poznań', .utc(2026, 11, 2));
});
// …
testWidgets('the agent draws the order and the user removes a line', (
tester,
) async {
final agent = ScriptedAgent([
(_) => [
AgentStep.showView(const DeskCatalog().example),
const AgentStep.say('Here is your order.'),
],
]);
await tester.pumpWidget(
MaterialApp(
home: BlocProvider.value(
value: cubit,
child: TandemScope.connected(
surface: (context) => context.read<OrderDeskCubit>(),
connection: agent,
approvals: const .fromState(),
child: const Column(
children: [
TandemView(catalog: DeskCatalog()),
Expanded(child: AgentChat()),
],
),
),
),
),
);
await tester.enterText(find.byType(TextField), 'Show me the order');
await tester.tap(find.text('Send'));
await tester.pumpAndSettle();
expect(find.byType(OrderLine), findsNWidgets(2));
// …
await tester.tap(find.text('Remove').first);
await tester.pumpAndSettle();
expect(cubit.order.lines, hasLength(1));
// …
});The tap goes through setQuantity with the view as the caller, the same way as on a device. Point the example at a path the screen does not list and the test fails: Tandem refuses the view and draws nothing. In debug, TandemView also reports such an example when it appears. Keep this test passing before using the catalog with a model. A component or property name the catalog does not have stops the build.
For a demo that draws on every run, use ScriptedAgent.. The example app's order desk runs on one without a key.
Your coding agent can draw on the same TandemView. While the view is on the screen, ext. lists tandem_show_view among the screen's tools, and ext. draws with it.
What you see: the test passes in a second. Break the example and it fails on the first expectation.
One desk for the whole app
One TandemScope above the navigator gives the app one session and one thread, so the conversation goes on as the user moves between screens. Put the scope in MaterialApp. with a surface that stands for the whole app. The example's test does it with a script in place of a backend:
MaterialApp(
navigatorKey: routes.key,
navigatorObservers: [routes],
initialRoute: '/desk',
// …
builder: (context, child) => TandemScope.connected(
surface: (context) => shop,
connection: ScriptedAgent([
(_) => [
AgentStep.showView(const DeskCatalog().example),
const AgentStep.callTool('place_order'),
],
]),
approvals: const .fromState(),
// Above the navigator, the desk brings its own overlay, for the
// tooltips of its widgets.
child: Overlay(
initialEntries: [
OverlayEntry(
builder: (context) {
session = TandemSessionScope.of(context);
return Material(
child: Column(
children: [
Expanded(child: child ?? const SizedBox()),
const SingleChildScrollView(
child: TandemView(catalog: DeskCatalog()),
),
],
),
);
},
),
],
),
),
),A scope above the navigator is also above the navigator's Overlay. Widgets with tooltips, such as the − and + of OrderLine, need one, so the scope's child brings its own Overlay, with a Material for the widgets inside. In an app, the chat and the approval cards that . leaves to you (approvals) go there too. A catalog for the whole app can list a whole design system, @TandemCatalog([..
The surface is a facade. Its getters and methods delegate to the desk's cubit, and agentCapabilities follows the current route. Its changes merges the cubit's stream with the route changes, so Tandem reads the list again when the route changes:
/// The surface of the whole app: its list follows the route.
@TandemAgent()
final class ShopAgent({
required final OrderDeskCubit desk,
required final RouteTracker routes,
}) with _$ShopAgent {
@override
List<AgentCapability> get agentCapabilities => switch (routes.current) {
'/desk' => [
.sees(order),
.calls(setQuantity),
if (desk.canPlace) .callsWithApproval(placeOrder),
.calls(openCatalog),
],
'/catalog' => [.sees(catalog), .calls(openDesk)],
_ => [.calls(openDesk)],
};
@override
Stream<Object?> get changes => Stream.multi((controller) {
final subscriptions = [
desk.stream.listen(controller.add),
routes.changes.listen(controller.add),
];
controller.onCancel = () async {
for (final subscription in subscriptions) {
await subscription.cancel();
}
};
}, isBroadcast: true);
/// The order as the user sees it on the desk.
DeskOrder get order => desk.order;
// …
/// Opens the catalog of products.
void openCatalog() => routes.push('/catalog');
/// Opens the order desk.
void openDesk() => routes.push('/desk');
}RouteTracker is a NavigatorObserver that reports every route change:
/// Reports every route change, so that the agent list can follow it.
final class RouteTracker() extends NavigatorObserver {
final key = GlobalKey<NavigatorState>();
final _changes = StreamController<Object?>.broadcast();
String? current;
Stream<Object?> get changes => _changes.stream;
void push(String route) => key.currentState?.pushNamed(route);
// …
}Navigation is a listed method, so the agent moves the user the way a button would. When the route changes, the list changes with it: the old screen's data and methods are gone, a pending approval request is invalidated (approvals), and a view bound to the old screen's data loses those components until the user is back. The catalog's widgets call nothing on their own. A press goes through the listed method, so approvals and refusals hold on every screen.
What one desk does not give: a chat per screen, since there is one thread; several views at once, since there is one TandemView; a conversation after a restart, since the thread lives in memory (roadmap).
What you see: the chat follows the user from the catalog to the desk. On the catalog route, the order's rows and customer card disappear; the title and disabled Place order button remain. Returning to the desk restores the rows and customer card.
Where to go next
- Approvals: what
.does to a press, and howcallsWithApproval .draws the cards.fromState() - Keep the conversation: a
TandemThreadoutside the screen when each screen has its own scope. - Testing:
ScriptedAgent,AgentRequestandTandemBridge..call - Roadmap: fields with approval, several views on one screen, drawing while the agent streams, saved conversations.
- Glossary: View, Catalog, Component, Action, Caller.