Quickstart for Flutter
This page is for a Flutter developer. It takes you from flutter create to a screen that a manager published in HotLayout and that your app draws. Plan for half an hour.
The Dart code blocks are fragments of the package's example/ app, which is compiled and tested with the package; a test of the package checks that every Dart block here is a verbatim fragment of it.
The steps only get you there. Every parameter of renderDocument, the standard actions, sentences and number formats, transitions, live data, reports, and what the renderer guarantees for each widget are in the Flutter reference; each step ends with a link to the part that belongs to it.
Related pages: index · Flutter reference · delivery · data dictionary · theme · localization · compatibility · widgets · quickstart for React
What you are integrating#
| Piece | What it is |
|---|---|
| Document | One JSON file: a set of screens built from widgets. Published by the builder as published.json. |
| Theme | One JSON file: the token names the project has (primary, md, titleM, and names of your own such as brandCoral) and the values behind them. |
| Data | A map your app supplies: values for the paths the document is bound to (task.title, cart.count). |
| Renderer | The hotlayout_flutter package: Dart code that turns the three into Flutter widgets. |
The package reads document contract 9.x and theme contract 4.x. The major version must match; a document that uses a field newer than the package still opens, and the package skips the field. Details: The package. Which package version reads which schema minor: the changelog.
The steps:
- Add the dependency
- Bundle a fallback copy
- Load the theme and name the document source
- Load the document
- Draw the document
- Supply data
- Handle actions
- Accept what the user wrote
- Pick the language
- Versions: what a user sees
After the steps: Show a placement, Test the screen, Platform notes, Fonts and What to check when nothing shows up.
1. Add the dependency#
flutter pub add hotlayout_flutteror in pubspec.yaml:
dependencies:
hotlayout_flutter: ^0.33.0The package is on pub.dev and requires Dart SDK ^3.11.5. There is one import, and nothing under src/ is public:
import 'package:hotlayout_flutter/hotlayout_flutter.dart';The repository contains an example/ app: this page, complete, in three files. lib/main.dart there is the host; you can copy it into a new app as it is.
Details: The package — dependencies, the icon set and its licence notices.
2. Bundle a fallback copy#
The renderer never shows an empty screen because the network failed. It draws a copy from your app bundle first and replaces it when the network answers. You provide that copy.
What to ask for#
A developer often has no access to the admin. If someone else built the screen, ask them for these four things — the rest of this page needs nothing else:
| What | Where it is in the admin |
|---|---|
| The address of the published document — or three ids: organization, project, document | The list of documents, Copy address for the app on the row of a published document. The document id stands under the document's name in the same list. |
| The address of the published theme | Project settings → Delivery → Address of the published theme. With the organization and project ids you can write it yourself — see step 3. |
The data dictionary, data-contract.json |
Project settings → Data dictionary → Open the dictionary → Download data-contract.json. It lists the values and lists your app supplies. |
| A copy of the document and of the theme to bundle with the app | Nothing to export: open the two addresses and save what they return. |
To see which values one particular document reads, run the short script in What a document reads over its file.
The two files#
Put two files into your app:
- a copy of the document you expect to show, and
- a copy of the theme.
For a screen that is already published there is nothing to export: the two published addresses return exactly these files — open them and save the answers. To try the renderer before you have a project, take the two files of the example — example/assets/hotlayout/document.json and theme.json (the rewards-showcase fixture of the contract and its theme) — together with example/lib/backend.dart, the data that document is bound to.
# pubspec.yaml of your app
flutter:
assets:
- assets/hotlayout/document.json
- assets/hotlayout/theme.jsonconst documentAsset = 'assets/hotlayout/document.json';
const themeAsset = 'assets/hotlayout/theme.json';Both loaders read from rootBundle at the path you pass, so the files must be declared in your app. Always pass assetPath: the default points at a file of the package's own demo.
3. Load the theme and name the document source#
Read the theme before the first frame. Replacing colors after the screen is drawn is a visible jump; the loader has its own three-second timeout (kThemeFetchTimeout) and never throws.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final transport = HttpDocumentTransport();
// The theme is read BEFORE the first frame: replacing colors after the
// screen is drawn is a visible jump. Neither call throws.
final themeLoad = themeUrl.isEmpty
? await ThemeLoad.fromBundle(assetPath: themeAsset)
: await ThemeLoad.fromNetwork(
Uri.parse(themeUrl),
transport: transport,
assetPath: themeAsset,
);
if (themeLoad.isFallback) {
debugPrint('theme fallback: ${themeLoad.status.name} ${themeLoad.detail ?? ''}');
}
const bundled = BundledDocumentSource(title: 'Bundled copy', assetPath: documentAsset);
final DocumentSource source = documentUrl.isEmpty
? bundled
: PublishedDocumentSource(
url: Uri.parse(documentUrl),
fallback: bundled,
transport: transport,
);With empty addresses the app shows the bundled copies — enough to see your first screen. To read the published files, run with the two addresses (flutter run --dart-define=documentUrl=https://… --dart-define=themeUrl=https://…). The addresses of a published document and theme:
https://firebasestorage.googleapis.com/v0/b/ui-builder-dd4af.firebasestorage.app/o/orgs%2F<orgId>%2Fprojects%2F<projectId>%2Fdocuments%2F<documentId>%2Fpublished.json?alt=media
https://firebasestorage.googleapis.com/v0/b/ui-builder-dd4af.firebasestorage.app/o/orgs%2F<orgId>%2Fprojects%2F<projectId>%2Ftheme%2Fpublished.json?alt=mediaThe host and the bucket are the same for every project; replace <orgId>, <projectId> and <documentId> with your three ids and keep everything else: %2F is an encoded /, and without ?alt=media the address returns a description of the file instead of the file. The object path is orgs/{orgId}/projects/{projectId}/documents/{documentId}/published.json. Both files are readable without a token. The ready addresses are also in the admin: Copy address for the app in the list of documents, and Project settings → Delivery.
Before the first run with addresses on macOS or in an Android release build: the app needs a network permission that flutter create does not give, and without it nothing fails — every request becomes unreachable and the bundled copies are shown. Add it now: Platform notes.
This is the direct address. In production most teams serve the document from their own backend, which receives every publication by webhook; the app then reads an address of yours, and nothing else on this page changes.
ThemeLoad never throws: ThemeLoad.status is ok when the theme you asked for is in use, and any other value means a fallback. Details: Theme; the fallback order is on the theme page.
4. Load the document#
Load in two steps: the bundled copy at once, the network after.
Future<void> _read() async {
// 1. Draw the bundled copy at once: no loading state.
final seed = widget.source.seed;
if (seed != null) _show(await seed.load());
// 2. Ask the network. This never throws because of the network.
_show(await widget.source.load());
}load() returns a DocumentLoad with the document, the status (why this document is on screen), isFallback and the signature of the JSON text. A fallback is silent on screen by design, so log the status. Most re-reads bring the same document, so keep what is on screen when the signature did not change:
void _show(DocumentLoad next) {
if (!mounted) return;
// A fallback is silent on screen by design, so say it in the log.
debugPrint('document: ${next.status.name} ${next.detail ?? ''}');
final previous = _load;
// A refresh that failed keeps the published document on screen rather
// than going back to the bundled copy.
if (previous != null && next.isFallback && !previous.isFallback) return;
// Most re-reads bring the same document: nothing to redraw. A new version
// is drawn at once, and the screen stack stays while its screens exist.
if (previous != null && previous.signature == next.signature) return;
setState(() => _load = next);
}To pick up a new publication without a restart, load again when the app returns to the foreground. Only a source whose isRefreshable is true can bring something new:
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Back from the background: a manager may have published meanwhile.
if (state == AppLifecycleState.resumed && widget.source.isRefreshable) {
widget.source.load().then(_show);
}
}Details: Network and the fallback — every DocumentLoad field and status value, your own HTTP stack, the transport details — and Live data and new versions for refreshing on a timer.
5. Draw the document#
Pick one theme from the set. The contract marks every theme light or dark, so you do not hard-code theme ids:
// The contract marks every theme light or dark: no theme ids in app code.
final theme = widget.themeLoad.contract.themeForBrightness(
MediaQuery.platformBrightnessOf(context),
);return Theme(
data: theme.toMaterialTheme(),
// The renderer draws only the document: the Scaffold and the safe area
// are the host's.
child: Scaffold(
body: SafeArea(
child: renderDocument(
document,
theme: theme,
data: widget.data,
locale: locale,
onRecordAction: _actions.handle,
onWrite: _onWrite,
// Documents from a source you do not fully trust: no autofill hints.
// autofill: false,
),
),
),
);The parameters you need now are theme, data, locale, onRecordAction and onWrite; steps 6 to 9 explain them. The widget keeps its own stack of screens, draws only the document (the Scaffold and the safe area are yours), and handles the system back button with nothing to wire.
Run the app now: you should see the screen.
Details: Rendering a document — every parameter and what the returned widget does and does not do — and The system back button.
6. Supply data#
data is a map from path to value. Flat and nested keys both work, and you can mix them:
const Map<String, Object?> backendData = {
// flat: the key is the whole path
'user.firstName': 'Alex',
'cart.count': 3,
'user.level': 3,
'user.isPremium': true,
'user.memberSince': '2025-03-14T09:00:00.000Z',
// nested: the path is walked segment by segment
'campaign': {'title': 'Autumn sale', 'endsAt': '2026-11-30T23:59:59.000Z'},A collection is a list of records under the collection name:
// a collection: a list of records under the collection name;
// a record uses field names (`title`), not full paths (`task.title`)
'tasks': [
{
'title': 'Confirm the delivery address',
'progress': 3,
'target': 5,
'completed': false,
'status': 'inProgress',
},Keep the types (a number stays a number, a date is an ISO 8601 string with time and zone), use field names inside a record (title, not task.title), and pass a new map when the values change. A missing value is not an error: the binding shows the fallback written in the document.
Which paths and collections exist is defined by the project's data dictionary; which of them one document reads is in the document — see What a document reads. What your backend returns is described in the backend guide.
Details: Data — the rules for types, dates and texts, sentences and number formats, "days left" and now, and Data of one screen, where scopeFor finds the rest of the entity that a tapped list row opens.
7. Handle actions#
The host gets an action through onRecordAction (the action, the id of the node and the record of that node); HostActions routes it by type, with one handler per action your app knows. The renderer performs none, navigate, navigate.back, navigate.section, setValue and toggleValue itself; everything else, and navigate.back on the first screen, reaches you. An action type you do not know is not an error: log it and do nothing.
// The app's own actions, one handler per type. A handler gets the action,
// the node and its `record`: the list row, or the row that opened this
// screen (a flat map of paths, or null).
late final _actions = HostActions(
handlers: {
// "Back" on the first screen of the document: leave the flow.
ButtonAction.navigateBack: (call) => Navigator.of(context).maybePop(),
'share': (call) => _say('Your share sheet opens here'),
// Which product? The row says so. Check the id on your backend like any
// user input before you add it to the cart.
'addToCart': (call) => _say('Add ${call.record?['item.name']} (${call.valueOf('item.id')}) to the cart?'),
},
onMiss: (call, reason) => debugPrint('unhandled action ${call.type} from ${call.nodeId}: ${reason.name}'),
);The action catalog#
A manager picks an action from a list in the builder: none, go to screen, go back, open a web page, open an app link, close the flow, or an "Other action" with a name of your own (share, addToCart). The renderer never opens an address by itself: openUrl, deeplink and close reach you parsed and checked, and you perform them. Open only what the package marked standard. The catalog, the checks, runStandardAction and the list of what stays with you are in the reference: The action catalog and Standard actions.
Details: Actions and navigation — HostActions (the handlers, onMiss, exclusive, onError), analytics (onTrack, onScreenShown), haptics, what a row's record holds (One screen, many records) and transitions.
8. Accept what the user wrote#
A screen can ask: text fields, switches, checkboxes, a choice group, and buttons that write a value (setValue, toggleValue). Each writes to a data path. The renderer keeps the written value for the lifetime of the screen stack, so conditions and bound texts on the same screen follow the user at once, and it calls onWrite at the same moment.
// What the user typed or switched in a `TextField`, `Switch`, `Checkbox` or
// `ChoiceGroup`: the data path of the field and a String, a bool or (a number
// `TextField`) a num; an empty String when the number was cleared. Called on
// every change, at once. It is user input: check it on your backend like any
// other, and throttle here if a network stands behind it.
void _onWrite(String path, Object? value) {
switch (value) {
case String text:
debugPrint('text field $path: ${text.length} characters');
case bool on:
debugPrint('switch or checkbox $path: $on');
case num number:
debugPrint('number field $path: $number');
}
}The value is String for a text field or a choice group, bool for a switch or a checkbox, num for a number field. Every change is written at once. The value is user input, and so is the path: check both on your backend, and pass writablePaths to say which paths a document may write. Errors are yours too — the renderer validates nothing.
Details: Forms, Write actions and A form for a survey.
After a write, supply the data that depends on it#
The renderer writes the value and tells you. It does not fetch or invent the data that follows from the choice — that is the host's job.
The typical case: a catalog screen with a choice group bound to item.selectedId, and a "Details" button that opens a screen bound to item.name, item.price, item.image. The user picks the second product and presses the button. The renderer wrote item.selectedId and opened the details screen — and that screen reads item.name from your data. If your data still holds nothing (or the first product), the screen shows fallback texts (or the first product), and nothing fails or is logged: a fallback is a legitimate state.
So on onWrite, put the record behind the choice into data and rebuild. In the State of the screen that hosts the document: keep the id the renderer wrote (when path == 'item.selectedId' and value is String, store it with setState), and build the map you pass as data: from your own catalog — {...widget.data, 'item': ?itemsById[_selectedId]}, where itemsById maps the id from the list to the fields of that item and 'item': ?x adds the entry only when x is not null. When the record has to be fetched, do it in onWrite and call setState when the answer arrives — the open screen picks the new data up on the rebuild.
The same holds for anything derived from input: a price that depends on a chosen plan, a list filtered by a switch, an error text for a typed phone number. A screen opened from a list row does not need this — the row carries its record itself (One screen, many records).
9. Pick the language#
A document carries all its languages; you show one. Pass the device locale as the platform gives it and let the document find its own language for it:
// The document matches the device languages against its own list:
// `ar-EG` finds `ar`. A user's choice wins over the device.
final locale =
widget.locale ??
document.localization?.localeFor(WidgetsBinding.instance.platformDispatcher.locales);A user's choice overrides the device: keep it in your state and pass it instead. The writing direction follows the language the document is shown in, with nothing to do on your side. The renderer's own four short texts (the back arrow label, a failed image, two version notices) are English until you pass labels:.
Details: Language and right-to-left — how a language is found, RendererLabels, direction — and the localization page.
10. Versions: what a user sees#
The same major version and an older or newer minor: the screen, and unknown parts degrade by the compatibility policy. Another major version read by PublishedDocumentSource: the bundled copy, with status incompatible, so a user on an old app keeps the screen that shipped with it. A document you pass to renderDocument directly gets a notice instead of the screen: "Update the app to see this screen." for a newer major, a neutral "not available" for an older one.
Details: Version compatibility — the table of verdicts, why the two notices differ, and versionVerdict for a document you obtained another way.
Show a placement#
Besides whole screens, the app can name small spots — home.banner — and a manager chooses in the admin which published document stands in each. In Flutter that is HotlayoutPlacement(name: 'home.banner', projectBase: …): it reads the placement map from the project folder, finds the document of the name and draws it, or draws a zero-size box and tells your code why so that you can fold the frame. The map, the layout of the folder, the reports and an example are on the Placements page; the widget is in Placements of the reference.
Test the screen#
In a widget test, assets are read outside the test's fake clock — load the theme and pump the screen inside tester.runAsync:
// Assets are read outside the fake clock of a widget test.
await tester.runAsync(() async {
final themeLoad = await ThemeLoad.fromBundle(assetPath: themeAsset);
expect(themeLoad.status, ThemeLoadStatus.ok);
await tester.pumpWidget(
MaterialApp(
home: HotLayoutScreen(
source: const BundledDocumentSource(title: 'Bundled copy', assetPath: documentAsset),
themeLoad: themeLoad,
data: backendData,
),
),
);
await Future<void>.delayed(const Duration(milliseconds: 200));
});
await tester.pumpAndSettle();For the network, give PublishedDocumentSource a fake DocumentTransport that returns a status code and a body; no HTTP mocking is needed. The whole test is example/test/widget_test.dart in the package.
Platform notes#
On two platforms a missing permission does not fail: every request becomes unreachable, the bundled copies are shown, and the network path is never exercised.
macOS. A sandboxed macOS build needs the com.apple.security.network.client entitlement in both macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements:
<key>com.apple.security.network.client</key>
<true/>This is the build you are most likely to look at during development.
Android. flutter create declares android.permission.INTERNET only in the debug and profile manifests. Add it to your app's main android/app/src/main/AndroidManifest.xml, or the release build will behave like the macOS case above:
<uses-permission android:name="android.permission.INTERNET"/>iOS. Nothing to add for HTTPS addresses.
Web. A Flutter web build is a page in a browser: the server of the document and the theme must allow cross-origin reads from your site's origin, and the transport must not add request headers. Our storage does not allow your origin by default, so a web build reads the files from your own backend — see Reading from a browser. Builds for iOS, Android and desktop are not affected.
Fonts#
A theme names its font families and their fallbacks; the package does not deliver font files. Until your app declares the family under flutter: fonts: with the same name, text is drawn in the platform's default font and nothing fails. See Fonts in the reference and theme.
What to check when nothing shows up#
Work down the list; each step rules out one layer.
- Is the bundled copy on screen instead of the published one? Log
load.statusandload.isFallback. A fallback is silent by design, so without this line "published but not shown" looks like a broken app. notPublished. The address answered 404. The document was not published yet, or the organization, project or document id in the URL is wrong. A saved draft is not a publication.unreachableon every run. Check the platform notes above first. On macOS this is almost always the missing entitlement.timedOut. The default is five seconds. Check the network, then pass a longertimeout.serverError. Logdetail; it contains the status code. A 403 means the address points at a file that is not public — onlypublished.jsonis.malformed. The answer is not a document. Open the URL in a browser: you should see JSON withschemaVersionandscreens.incompatible. The document was built for another major contract version. Update the package. See compatibility.network, but the screen did not change. The storage holds the same document as before. Comparesignaturevalues; then ask whether the change was published or only saved.- The details screen shows the wrong record or fallback texts after a choice. See After a write, supply the data that depends on it.
- The screen is there, the values are not. Bindings are showing their fallbacks. Check that the keys of
datamatch the paths of the data dictionary exactly, and that collections are lists under the collection name. - A block is missing. A
visibleIfcondition did not hold. A value that is absent counts as empty:isEmptyholds, every other operator does not. See compatibility. - A list is empty. The value under the collection name is not a
List, or the records use full paths (task.title) instead of field names (title). - Colors or fonts look wrong. Log
themeLoad.status. Anything butokmeans a fallback theme is shown. For fonts see the section above. - A placeholder with a widget name appears in debug builds only. The document contains a widget this renderer version does not know. Its children are still drawn; in release builds the placeholder is not shown.
- Text is in the wrong language. Log the
localeyou pass andload.document.shownLocale(locale). A missing translation shows the default-language text, not an empty space.
In debug builds the renderer prints what it decided not to draw, prefixed with [hotlayout].