Checkout and recovery
A single native phone journey: review the order and visible service fee, pay once, recover a lost response, then read the matching confirmed receipt. Priority actions stay pinned; content scrolls at large text. Amounts use the kit’s numeric roles and the layout follows the current host theme. The demo menu switches the same order between two host-owned designs — a stacked invoice on Hairline and a wallet review on the Soft preset — without restarting the session or the attempt.









Run the demo
Section titled “Run the demo”From example/:
flutter run -d <device-id> -t lib/checkout_block_demo.dart- Review Paket Belajar Rp100.000 + Biaya layanan Rp2.500 and pay the total.
- The default Respons hilang scenario loses the response. No receipt appears.
- Tap Cek status. The synthetic host confirms the same attempt; only then does its matching receipt appear. Selesai starts a fresh demo session.
The top bar is developer tooling: switch light/dark or open Menu demo. Under Tampilan, Invoice and Dompet switch the same order between the stacked invoice on Hairline and the wallet review on the Soft preset — the session, the typed receipt email and any live attempt survive the switch. Dompet offers Pakai metode lain, which opens a kit method sheet; choosing Virtual account asks the synthetic host for a new quote with the bank fee (total Rp104.000). Pay stays disabled and busy until that answer arrives, and a slower earlier answer never replaces a newer one. The wallet review shows the selected method and bank before Pay is available. Under Skenario, Pending lalu offline returns pending, fails the first check and confirms on the next check. Struk gagal dimuat confirms payment but fails the first receipt load; Lihat struk retries without sending another payment. Putar ulang restarts the current scenario and Kurangi gerakan turns kit motion off for the demo (it joins the OS reduce-motion flag rather than replacing it). Selecting a scenario or replaying deliberately resets the synthetic session; this is not a customer recovery action. The demo uses a fixed clock; elapsed time never decides payment status. Sharing returns dismissed and copying returns unavailable, without opening platform services.
Composition and ownership
Section titled “Composition and ownership”HostCheckoutJourney connects InvoiceCheckout or WalletReviewCheckout
(layout:) and HostPaymentRecovery. It accepts host data and async callbacks.
Place it in a bounded body such as Scaffold.body so the main action can stay
pinned. Both layouts render the same CheckoutOrder and CheckoutActions; the
wallet look passes showActionBar: false so the journey’s pinned footer keeps
the only pay action, and its “use another method” button opens a kit
showPaymentSheet with PaymentMethodPicker unless the host passes
onChangeMethod. While the host re-prices the selected method it sets
CheckoutOrder.quoting; Pay stays disabled and busy with the localized
“Updating total” hint, and submission revalidates that the quote is current,
unexpired and priced for the selected method.
| Concern | Existing surface |
|---|---|
| Item, visible fee and method review | PaymentSummary, PaymentMethodPicker, MerchantHeader |
| Wallet review alternative | WalletReviewCheckout, BalanceCard |
| One pinned action and large-text scroll | PaymentFullPageView, PaymentButton |
| Quote wait and method gating | CheckoutOrder.quoting, PaymentQuote.methodId |
| Same-attempt recovery | PaymentAttempt, PaymentStatusView, PaymentAction |
| Confirmed receipt | PaymentReceipt, PaymentReceiptData |
| Shared look | PaymentTheme, scoped button/field themes, named host pay preset |
Read the checkout contract for quote expiry, method readiness, changed terms, authorization and session identity. Read status/recovery for restored attempts and receipt gating. Those rules apply equally when you change this layout.
The real host must durably persist the attempt before sending, enforce server-side idempotency and price/auth rules, parse provider responses, and validate receipts. The example guards the receipt’s transaction reference; that is not full backend receipt validation. No elapsed delay establishes success or failure. Never turn a status check or a missing response into a new submission.
Copy the source
Section titled “Copy the source”Copy all three compositions below and inject your own callbacks. CheckoutOrder
is a host model you can adapt. The standalone shell and adapter show wiring with
synthetic data; replace them with your backend and platform adapters.
Theme-dependent presets resolve from the current context.
Source: compositions/host_checkout.dart
Open this file on GitHub. Copy and adapt it in your host app.
// Example host code, not kit API (D98 host adoption).//// Two checkout layouts built from the same kit components, the same host// model and the same host callbacks. The host owns every decision: the// quote, the selected method, the balance verdict and what "pay" does. These// widgets only arrange kit components; they make no network or payment call.//// Styling follows the D98 adoption order: shared tokens from the app theme,// one product look for buttons and fields applied as a scoped theme, and one// named host preset for the pay action that both layouts share. Everyday// buttons and fields here take no `style`.
import 'package:flutter/material.dart';import 'package:rakit_ui/rakit_ui.dart';
/// The host's checkout state. Immutable; the host rebuilds it on change.class CheckoutOrder { const CheckoutOrder({ required this.merchant, required this.reference, required this.quote, required this.methods, required this.selectedMethodId, required this.balance, required this.balanceState, this.merchantVerified = false, this.receiptEmail = '', this.paying = false, this.quoting = false, });
final String merchant;
/// Set only when the host has verified this merchant. final bool merchantVerified; final String reference; final PaymentQuote quote; final List<PaymentMethod> methods; final String? selectedMethodId; final Money balance; final BalanceState balanceState; final String receiptEmail;
/// True while the host is paying, so both layouts block a second press. final bool paying;
/// True while the host re-prices the selected method. Both layouts keep /// Pay disabled until a quote for the current method arrives. final bool quoting;}
/// The host's callbacks. Both layouts report intent through the same set.class CheckoutActions { const CheckoutActions({ required this.onSelectMethod, required this.onChangeMethod, required this.onReceiptEmailChanged, required this.onPay, });
final ValueChanged<PaymentMethod> onSelectMethod; final VoidCallback onChangeMethod; final ValueChanged<String> onReceiptEmailChanged;
/// The host pays. The button stays busy until the future completes. final Future<void> Function() onPay;}
/// Which review body a host checkout screen renders. Both share the same/// pinned action, callbacks, quote and recovery; only the arrangement of/// kit components differs.enum CheckoutLayout { invoice, wallet }
/// The product's shared button and field look, as theme extensions. It/// reads the current theme, so light, dark and brand changes follow.List<ThemeExtension<dynamic>> productLooks(BuildContext context) { final theme = PaymentTheme.of(context); return [ PaymentButtonTheme( style: PaymentButtonStyle( borderRadius: BorderRadius.circular(theme.space(PaymentSpace.major)), ), ), PaymentFieldTheme( fillColor: theme.surfaceMuted, borderRadius: BorderRadius.circular(theme.space(PaymentSpace.group)), ), ];}
/// Applies [productLooks] to a subtree, keeping the parent's other/// extensions (the payment theme included).class ProductLooks extends StatelessWidget { const ProductLooks({super.key, required this.child});
final Widget child;
@override Widget build(BuildContext context) { final parent = Theme.of(context); return Theme( data: parent.copyWith( extensions: [...parent.extensions.values, ...productLooks(context)], ), child: child, ); }}
/// Named host preset for the checkout's pay action, shared by both layouts./// An ink fill on the surface color: high contrast in light and dark.PaymentButtonStyle payActionStyle(BuildContext context) { final theme = PaymentTheme.of(context); return PaymentButtonStyle( backgroundColor: theme.textPrimary, foregroundColor: theme.surface, );}
String _t(BuildContext context, String en, String id) => Localizations.localeOf(context).languageCode == 'id' ? id : en;
String _payLabel(BuildContext context, Money total) => _t( context, 'Pay ${PaymentLocalizations.of(context).moneyFormat.format(total)}', 'Bayar ${PaymentLocalizations.of(context).moneyFormat.format(total)}',);
class _ReceiptEmail extends StatelessWidget { const _ReceiptEmail({required this.order, required this.actions});
final CheckoutOrder order; final CheckoutActions actions;
@override Widget build(BuildContext context) => PaymentTextField( label: _t(context, 'Email for receipt', 'Email untuk struk'), type: PaymentTextFieldType.email, initialValue: order.receiptEmail, onChanged: actions.onReceiptEmailChanged, );}
/// Layout one: a stacked invoice. Merchant, line items with fees, method/// choice, receipt email, then one full-width pay action at the end.class InvoiceCheckout extends StatelessWidget { const InvoiceCheckout({ super.key, required this.order, required this.actions, this.inlinePayAction = true, });
final CheckoutOrder order; final CheckoutActions actions;
/// A screen host can move this action into its pinned footer instead. final bool inlinePayAction;
@override Widget build(BuildContext context) { final theme = PaymentTheme.of(context); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: theme.space(PaymentSpace.section), children: [ MerchantHeader( name: order.merchant, orderReference: order.reference, verified: order.merchantVerified, ), PaymentSummary(quote: order.quote), PaymentSection( title: _t(context, 'Pay with', 'Bayar dengan'), child: PaymentMethodPicker( methods: order.methods, selectedId: order.selectedMethodId, onChanged: actions.onSelectMethod, ), ), _ReceiptEmail(order: order, actions: actions), if (inlinePayAction) PaymentButton( label: _payLabel(context, order.quote.total), style: payActionStyle(context), busy: order.paying, onPressed: actions.onPay, ), ], ); }}
/// Layout two: merchant and wallet details, with the review beside them on/// wide screens (under them on phones) and a pay action bar at the end.class WalletReviewCheckout extends StatelessWidget { const WalletReviewCheckout({ super.key, required this.order, required this.actions, this.showActionBar = true, });
final CheckoutOrder order; final CheckoutActions actions;
/// Set false when the host pins the same pay action itself, e.g. in a /// screen footer, so the review does not show two actions for one total. final bool showActionBar;
@override Widget build(BuildContext context) { final theme = PaymentTheme.of(context); final gap = theme.space(PaymentSpace.section); final type = PaymentType.of(context); final selectedMethod = order.methods .where((method) => method.id == order.selectedMethodId) .firstOrNull; final wallet = Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: gap, children: [ MerchantHeader( name: order.merchant, orderReference: order.reference, verified: order.merchantVerified, ), if (selectedMethod != null && selectedMethod.kind != PaymentMethodKind.balance) PaymentSection( title: _t(context, 'Pay with', 'Bayar dengan'), child: Column( crossAxisAlignment: CrossAxisAlignment.start, spacing: theme.space(PaymentSpace.inline), children: [ Text(selectedMethod.label, style: type.body), if (selectedMethod.detail case final detail?) Text(detail, style: type.caption), ], ), ) else BalanceCard(state: order.balanceState, balance: order.balance), PaymentButton( label: _t(context, 'Use another method', 'Pakai metode lain'), variant: PaymentButtonVariant.secondary, onPressed: actions.onChangeMethod, ), _ReceiptEmail(order: order, actions: actions), ], ); final review = PaymentSummary( quote: order.quote, title: _t(context, 'Review', 'Tinjau'), ); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: gap, children: [ LayoutBuilder( builder: (context, constraints) => constraints.maxWidth >= 600 ? Row( crossAxisAlignment: CrossAxisAlignment.start, spacing: gap, children: [ Expanded(child: wallet), Expanded(child: review), ], ) : Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: gap, children: [wallet, review], ), ), if (showActionBar) PaymentActionBar( total: order.quote.total, action: PaymentButton( label: _t(context, 'Pay from wallet', 'Bayar dari dompet'), width: PaymentWidth.hug, style: payActionStyle(context), busy: order.paying, onPressed: order.balanceState == BalanceState.sufficient ? actions.onPay : null, ), ), ], ); }}Source: compositions/host_checkout_journey.dart
Open this file on GitHub. Copy and adapt it in your host app.
// Host application source, not package API. Copy and adapt the callbacks// to your own adapters, persistence and routing.import 'dart:async';
import 'package:flutter/material.dart';import 'package:rakit_ui/rakit_ui.dart';
import 'host_checkout.dart';import 'host_payment_recovery.dart';
/// One bounded screen from review through recovery to a confirmed receipt.////// The host supplies a quote already priced for the selected method. Requote/// in [onSelectMethod] and rebuild [order] before allowing submission; while/// [CheckoutOrder.quoting] is true the pinned pay action stays disabled and/// busy. No challenge is performed here: this example's wallet needs none./// A host requiring authorization must finish that step before exposing this/// send step, and keep its credentials and cancellation handling outside it.class HostCheckoutJourney extends StatefulWidget { const HostCheckoutJourney({ super.key, required this.order, required this.clock, required this.newAttemptId, required this.onSelectMethod, required this.onReceiptEmailChanged, required this.onSubmit, required this.onCheckStatus, required this.onLoadReceipt, required this.onOtherAction, required this.onDone, required this.onShare, required this.onCopy, this.layout = CheckoutLayout.invoice, this.onChangeMethod, });
final CheckoutOrder order;
/// Which review body to render; recovery is shared by both layouts. final CheckoutLayout layout;
/// What the wallet layout's "use another method" action does. When null, /// the journey opens a kit [PaymentMethodPicker] sheet over the review; /// pass a callback to use a host-owned picker flow instead. final VoidCallback? onChangeMethod; final DateTime Function() clock; final String Function() newAttemptId; final ValueChanged<PaymentMethod> onSelectMethod; final ValueChanged<String> onReceiptEmailChanged;
/// Persist the attempt before sending. A lost response returns null or /// throws; both leave the result unknown and preserve this attempt ID. /// This is a send callback, not an authorization challenge callback. final Future<PaymentStatusSnapshot?> Function( PaymentAttempt attempt, CheckoutOrder order, ) onSubmit; final Future<PaymentStatusSnapshot> Function(PaymentAttempt) onCheckStatus; final Future<PaymentReceiptData> Function(PaymentAttempt) onLoadReceipt; final FutureOr<void> Function(PaymentAttempt, PaymentAction) onOtherAction; final VoidCallback onDone; final Future<ShareOutcome> Function(ReceiptShareData) onShare; final Future<bool> Function(String) onCopy;
@override State<HostCheckoutJourney> createState() => _HostCheckoutJourneyState();}
class _HostCheckoutJourneyState extends State<HostCheckoutJourney> { PaymentAttempt? _attempt; CheckoutOrder? _submittedOrder; PaymentReceiptData? _receipt; PaymentAction? _busyAction; bool _working = false; bool _receiptFailed = false; int _generation = 0;
@override void didUpdateWidget(HostCheckoutJourney oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.order.reference != widget.order.reference) { // A different host order starts another session. Never let a response // belonging to the previous order populate this one. _generation++; _attempt = null; _submittedOrder = null; _receipt = null; _busyAction = null; _working = false; _receiptFailed = false; } }
bool get _canPay { final order = widget.order; final methodId = PaymentMethodPicker.validSelection( order.methods, order.selectedMethodId, ); final method = methodId == null ? null : order.methods.firstWhere((method) => method.id == methodId); return !_working && !order.paying && !order.quoting && _attempt == null && method != null && order.quote.methodId == method.id && !order.quote.isExpiredAt(widget.clock()) && (method.kind != PaymentMethodKind.balance || order.balanceState == BalanceState.sufficient); }
bool _current(int generation, String id) => mounted && generation == _generation && _attempt?.attemptId == id;
/// The wallet layout's escape to method choice. Hosts can replace the /// default kit sheet with their own picker through /// [HostCheckoutJourney.onChangeMethod]. void _changeMethod(BuildContext context) { final override = widget.onChangeMethod; if (override != null) { override(); return; } final order = widget.order; final id = Localizations.localeOf(context).languageCode == 'id'; showPaymentSheet<void>( context: context, builder: (sheetContext) => PaymentSheet( header: PaymentSheetHeader( title: id ? 'Pilih metode' : 'Choose a method', onClose: () => Navigator.of(sheetContext).pop(), ), body: PaymentMethodPicker( methods: order.methods, selectedId: order.selectedMethodId, onChanged: (method) { widget.onSelectMethod(method); Navigator.of(sheetContext).pop(); }, ), ), ); }
Future<void> _submit() async { // Revalidate at the event boundary, including expiry since the last build. if (!_canPay) { setState(() {}); return; } final order = widget.order; final attempt = PaymentAttempt( attemptId: widget.newAttemptId(), quoteId: order.quote.id, quoteRevision: order.quote.revision, methodId: order.selectedMethodId!, submission: SubmissionState.sending, ); final generation = _generation; setState(() { _attempt = attempt; _submittedOrder = order; _working = true; }); PaymentStatusSnapshot? response; try { response = await widget.onSubmit(attempt, order); } catch (_) { // Transport failure cannot establish that a debit failed. } if (!_current(generation, attempt.attemptId)) return; setState(() { _attempt = response == null ? attempt.copyWith(submission: SubmissionState.outcomeUnknown) : attempt.reconcile(response).attempt; if (_attempt!.submission == SubmissionState.sending) { _attempt = attempt.copyWith(submission: SubmissionState.outcomeUnknown); } _working = false; }); if (_attempt!.status == PaymentStatus.succeeded) { await _action(attempt.attemptId, PaymentAction.viewReceipt); } }
Future<void> _loadReceipt(int generation, String id) async { final receipt = await widget.onLoadReceipt(_attempt!); if (!_current(generation, id)) return; if (_attempt!.status != PaymentStatus.succeeded || receipt.transactionId != _attempt!.serverReference) { throw StateError('Receipt does not belong to this confirmed payment'); } setState(() => _receipt = receipt); }
Future<void> _action(String id, PaymentAction action) async { final attempt = _attempt; if (_working || attempt == null || attempt.attemptId != id || !attempt.availableActions.contains(action)) { return; } final generation = _generation; setState(() { _working = true; _busyAction = action; _receiptFailed = false; if (action == PaymentAction.checkStatus) { _attempt = attempt.copyWith(observation: Observation.refreshing); } }); try { if (action == PaymentAction.checkStatus) { final response = await widget.onCheckStatus(attempt); if (!_current(generation, id)) return; final result = _attempt!.reconcile(response); setState(() { _attempt = result.applied ? result.attempt.copyWith(lastCheckedAt: widget.clock()) : _attempt!.copyWith(observation: Observation.unavailable); }); if (_attempt!.status == PaymentStatus.succeeded && _attempt!.availableActions.contains(PaymentAction.viewReceipt)) { await _loadReceipt(generation, id); } } else if (action == PaymentAction.viewReceipt) { await _loadReceipt(generation, id); } else { await widget.onOtherAction(attempt, action); } } catch (_) { if (!_current(generation, id)) return; setState(() { if (_attempt!.status == PaymentStatus.succeeded) { _receiptFailed = true; } else { _attempt = _attempt!.copyWith(observation: Observation.unavailable); } }); } finally { if (_current(generation, id)) { setState(() { _working = false; _busyAction = null; }); } } }
@override Widget build(BuildContext context) { final id = Localizations.localeOf(context).languageCode == 'id'; final attempt = _attempt; return ProductLooks( child: Builder( builder: (context) { if (attempt != null) { return HostPaymentRecovery( attempt: attempt, amount: _submittedOrder!.quote.total, receipt: _receipt, busyAction: _busyAction ?? (attempt.submission == SubmissionState.sending ? PaymentAction.checkStatus : null), header: _receiptFailed ? PaymentBanner( tone: StatusTone.warning, title: id ? 'Struk belum tersedia' : 'Receipt unavailable', message: id ? 'Pembayaran berhasil. Coba muat struk lagi.' : 'Payment succeeded. Try loading the receipt again.', ) : null, onAction: _action, onDone: widget.onDone, onShare: widget.onShare, onCopy: widget.onCopy, ); } final order = widget.order; final l10n = PaymentLocalizations.of(context); final actions = CheckoutActions( onSelectMethod: widget.onSelectMethod, onReceiptEmailChanged: widget.onReceiptEmailChanged, onChangeMethod: () => _changeMethod(context), onPay: _submit, ); return PaymentFullPageView( title: id ? 'Tinjau pembayaran' : 'Review payment', primaryAction: PaymentButton( label: '${id ? 'Bayar' : 'Pay'} ' '${l10n.moneyFormat.format(order.quote.total)}', style: payActionStyle(context), busy: order.quoting, busyLabel: l10n.updatingTotal, onPressed: _canPay ? _submit : null, ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: PaymentTheme.of(context).space(PaymentSpace.group), children: [ if (!_canPay && !order.quoting) PaymentBanner( tone: StatusTone.warning, title: id ? 'Pembayaran belum dapat dikirim' : 'Payment not ready', message: id ? 'Host perlu memberikan quote yang masih berlaku, metode yang sesuai, dan saldo yang cukup.' : 'The host must provide a current quote, a matching available method and sufficient balance.', ), switch (widget.layout) { CheckoutLayout.invoice => InvoiceCheckout( order: order, inlinePayAction: false, actions: actions, ), CheckoutLayout.wallet => WalletReviewCheckout( order: order, actions: actions, showActionBar: false, ), }, ], ), ); }, ), ); }}Source: compositions/host_payment_recovery.dart
Open this file on GitHub. Copy and adapt it in your host app.
// Copyable host composition, not kit API. The host restores the attempt,// reconciles snapshots, loads receipts and implements all platform effects.import 'dart:async';
import 'package:flutter/material.dart';import 'package:rakit_ui/rakit_ui.dart';
/// One restored payment, rendered from the host's current state.////// Use in a bounded Scaffold body to keep the priority action pinned. Wrap/// it in the product's theme (for example ProductLooks from host_checkout.dart)./// No quote, attempt, status or receipt is created by this composition.class HostPaymentRecovery extends StatelessWidget { const HostPaymentRecovery({ super.key, required this.attempt, required this.amount, required this.onAction, required this.onDone, required this.onShare, required this.onCopy, this.receipt, this.busyAction, this.header, });
final PaymentAttempt attempt; final Money amount;
/// Reconcile or load a receipt for this ID; never submit a new payment /// when handling checkStatus. Return the future to retain busy protection. final FutureOr<void> Function(String attemptId, PaymentAction action) onAction; final VoidCallback onDone; final Future<ShareOutcome> Function(ReceiptShareData) onShare; final Future<bool> Function(String) onCopy;
/// Host-loaded data for the current transaction. Unconfirmed or mismatched /// data stays hidden, including after an official correction of success. final PaymentReceiptData? receipt; final PaymentAction? busyAction;
/// Host notices, such as a safe receipt-loading error. Status refresh /// failures use attempt.observation and retain the last trusted snapshot. final Widget? header;
@override Widget build(BuildContext context) { final indonesian = Localizations.localeOf(context).languageCode == 'id'; final data = receipt; final confirmed = attempt.submission == SubmissionState.accepted && attempt.status == PaymentStatus.succeeded; if (confirmed && data != null && data.transactionId == attempt.serverReference) { return PaymentFullPageView( title: indonesian ? 'Struk pembayaran' : 'Payment receipt', primaryAction: PaymentButton( label: indonesian ? 'Selesai' : 'Done', onPressed: onDone, ), child: PaymentReceipt( data: data, onShare: onShare, onCopyTransactionId: onCopy, ), ); } return PaymentStatusView( attempt: attempt, amount: amount, header: header, busyAction: busyAction, onAction: (action) => onAction(attempt.attemptId, action), ); }}Source: themes.dart
Open this file on GitHub. Copy and adapt it in your host app.
import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';import 'package:rakit_ui/rakit_ui.dart';
/// Three independent brands applied from outside the package, without forking.enum DemoBrand { ruangBayar, lumen, soft }
ThemeData buildTheme(DemoBrand brand, Brightness brightness) { final dark = brightness == Brightness.dark; switch (brand) { case DemoBrand.ruangBayar: // "Hairline": white page, navy-black ink, rules instead of cards. // Colors are contrast-checked in docs/design-research.md, section 0. final ink = dark ? const Color(0xFFECEDF0) : const Color(0xFF1A1F36); final surface = dark ? const Color(0xFF131417) : Colors.white; final scheme = ColorScheme.fromSeed( seedColor: const Color(0xFF1A1F36), brightness: brightness, dynamicSchemeVariant: DynamicSchemeVariant.monochrome, primary: ink, onPrimary: surface, surface: surface, onSurface: ink, ); final payment = PaymentTheme.fromColorScheme(scheme).copyWith( accent: ink, onAccent: surface, surface: surface, surfaceMuted: dark ? const Color(0xFF1C1E23) : const Color(0xFFF5F6F8), outline: dark ? const Color(0xFF2C2E35) : const Color(0xFFE3E6EC), textPrimary: ink, textSecondary: dark ? const Color(0xFFA2A8B5) : const Color(0xFF5E6678), // Control edge 3.37:1 light, 4.85:1 dark; disabled labels stay above // 2:1 on the muted fill. border: dark ? const Color(0xFF7E838E) : const Color(0xFF868C9A), disabled: dark ? const Color(0xFF62656E) : const Color(0xFFA6ABB5), ); return _base(scheme, payment, background: surface); case DemoBrand.lumen: // "Contrast": pure black and white and heavier amounts, with the same // corners as Hairline (radius 8). final ink = dark ? Colors.white : Colors.black; final surface = dark ? const Color(0xFF0F0F0F) : Colors.white; final scheme = ColorScheme.fromSeed( seedColor: Colors.black, brightness: brightness, dynamicSchemeVariant: DynamicSchemeVariant.monochrome, primary: ink, onPrimary: surface, surface: surface, onSurface: ink, ); final payment = PaymentTheme.fromColorScheme(scheme).copyWith( accent: ink, onAccent: surface, surface: surface, surfaceMuted: dark ? const Color(0xFF1F1F1F) : const Color(0xFFF3F3F3), outline: dark ? const Color(0xFF333333) : const Color(0xFFE8E8E8), textPrimary: ink, textSecondary: dark ? const Color(0xFFB3B3B3) : const Color(0xFF545454), radius: 8, amountWeight: FontWeight.w700, ); return _base(scheme, payment, background: surface); case DemoBrand.soft: // "Soft": a tinted page with white inset panels, an indigo accent, // rounder corners and a lighter amount. Tokens only; the panels are // host styling (SoftInsetPanel). Contrast on the tinted page: body // text 14.3:1, secondary 5.6:1, accent 6.3:1, control edge 3.5:1, // status tones at least 5.6:1 (docs/design-research.md, section 9). final page = dark ? const Color(0xFF0E0F13) : const Color(0xFFF1F2F6); final surface = dark ? const Color(0xFF18191E) : Colors.white; final ink = dark ? const Color(0xFFECEDF1) : const Color(0xFF1C2133); final accent = dark ? const Color(0xFFAEB7FF) : const Color(0xFF3D4AC4); final onAccent = dark ? page : Colors.white; final scheme = ColorScheme.fromSeed( seedColor: const Color(0xFF3D4AC4), brightness: brightness, primary: accent, onPrimary: onAccent, surface: surface, onSurface: ink, ); final payment = PaymentTheme.fromColorScheme(scheme).copyWith( accent: accent, onAccent: onAccent, surface: surface, surfaceMuted: dark ? const Color(0xFF212329) : const Color(0xFFF4F5F9), outline: dark ? const Color(0xFF2E3038) : const Color(0xFFE2E4EB), textPrimary: ink, textSecondary: dark ? const Color(0xFFA4AAB7) : const Color(0xFF586074), border: dark ? const Color(0xFF7F8592) : const Color(0xFF7A8090), disabled: dark ? const Color(0xFF62656E) : const Color(0xFFA3A8B4), // D101 radius roles: 8 tags, 12 controls, 16 boxes, 20 sheets. radius: 16, controlRadius: 12, sheetRadius: 20, amountWeight: FontWeight.w500, ); // D102: fields stay white on the tinted page. return _base( scheme, payment, background: page, field: PaymentFieldTheme(fillColor: surface), ); }}
ThemeData _base( ColorScheme scheme, PaymentTheme payment, { required Color background, PaymentFieldTheme? field,}) { final controlRadius = payment.controlBorderRadius; return ThemeData( colorScheme: scheme, useMaterial3: true, splashFactory: switch (defaultTargetPlatform) { TargetPlatform.iOS => NoSplash.splashFactory, TargetPlatform.android when !kIsWeb => InkSparkle.splashFactory, _ => null, }, scaffoldBackgroundColor: background, extensions: [payment, ?field], dividerTheme: DividerThemeData(color: payment.outline, space: 1), appBarTheme: AppBarTheme( backgroundColor: background, foregroundColor: payment.textPrimary, surfaceTintColor: Colors.transparent, scrolledUnderElevation: 0, centerTitle: false, titleTextStyle: TextStyle( fontSize: 17, height: 24 / 17, letterSpacing: 0, fontWeight: FontWeight.w600, color: payment.textPrimary, ), shape: Border(bottom: BorderSide(color: payment.outline)), ), // Demo/Scenarios/Gallery switcher: a plain bar with a hairline, the // selected destination in ink, no tonal pill. navigationBarTheme: NavigationBarThemeData( backgroundColor: background, surfaceTintColor: Colors.transparent, indicatorColor: Colors.transparent, height: 64, iconTheme: WidgetStateProperty.resolveWith( (states) => IconThemeData( size: 24, color: states.contains(WidgetState.selected) ? payment.textPrimary : payment.textSecondary, ), ), labelTextStyle: WidgetStateProperty.resolveWith( (states) => TextStyle( fontSize: 12, fontWeight: FontWeight.w500, color: states.contains(WidgetState.selected) ? payment.textPrimary : payment.textSecondary, ), ), ), snackBarTheme: SnackBarThemeData( behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: controlRadius), ), dialogTheme: DialogThemeData( backgroundColor: payment.surface, surfaceTintColor: Colors.transparent, shape: RoundedRectangleBorder(borderRadius: payment.sheetBorderRadius), ), bottomSheetTheme: BottomSheetThemeData( backgroundColor: payment.surface, surfaceTintColor: Colors.transparent, ), popupMenuTheme: PopupMenuThemeData( color: payment.surface, surfaceTintColor: Colors.transparent, shape: RoundedRectangleBorder( borderRadius: controlRadius, side: BorderSide(color: payment.outline), ), ), // Plain Material buttons in example screens match PaymentButton: 6 px // corners, ink outline, no pill. filledButtonTheme: FilledButtonThemeData( style: FilledButton.styleFrom( shape: RoundedRectangleBorder(borderRadius: controlRadius), ), ), outlinedButtonTheme: OutlinedButtonThemeData( style: OutlinedButton.styleFrom( foregroundColor: payment.textPrimary, side: BorderSide(color: payment.border), shape: RoundedRectangleBorder(borderRadius: controlRadius), ), ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( foregroundColor: payment.textPrimary, shape: RoundedRectangleBorder(borderRadius: controlRadius), ), ), // Chips in example screens (sheet filters, the scenario picker): small // corners, no check mark, selection shown by an ink outline. chipTheme: ChipThemeData( showCheckmark: false, backgroundColor: payment.surface, selectedColor: payment.surfaceMuted, side: WidgetStateBorderSide.resolveWith( (states) => BorderSide( color: states.contains(WidgetState.selected) ? payment.accent : payment.outline, ), ), shape: RoundedRectangleBorder(borderRadius: controlRadius), labelStyle: TextStyle(fontSize: 14, color: payment.textPrimary), ), checkboxTheme: CheckboxThemeData( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), ), inputDecorationTheme: InputDecorationTheme( filled: true, fillColor: payment.surface, border: OutlineInputBorder( borderRadius: controlRadius, borderSide: BorderSide(color: payment.textSecondary), ), enabledBorder: OutlineInputBorder( borderRadius: controlRadius, borderSide: BorderSide(color: payment.border), ), focusedBorder: OutlineInputBorder( borderRadius: controlRadius, borderSide: BorderSide(color: payment.accent, width: 2), ), ), );}Source: checkout_block_demo.dart
Open this file on GitHub. Copy and adapt it in your host app.
import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_localizations/flutter_localizations.dart';import 'package:rakit_ui/rakit_ui.dart';
import 'compositions/host_checkout.dart';import 'compositions/host_checkout_journey.dart';import 'themes.dart';
void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); runApp(const CheckoutBlockDemo());}
enum CheckoutDemoScenario { lostResponse, pendingOffline, receiptRetry }
/// The two host-owned designs one checkout model can wear: the stacked/// invoice on Hairline, or the wallet review on the Soft preset.enum CheckoutDemoLook { invoice, wallet }
/// Synthetic adapter for this runnable example only. Replace it with host/// persistence and authoritative APIs. Delay never determines a verdict.class CheckoutDemoHost { CheckoutDemoHost({ this.scenario = CheckoutDemoScenario.lostResponse, this.delay = const Duration(milliseconds: 500), });
final CheckoutDemoScenario scenario; final Duration delay; final submittedIds = <String>[]; final checkedIds = <String>[]; int receiptLoads = 0; CheckoutOrder? sentOrder; final now = DateTime(2026, 11, 4, 10, 42);
PaymentStatusSnapshot snapshot( PaymentAttempt attempt, PaymentStatus status, ) => PaymentStatusSnapshot( attemptId: attempt.attemptId, serverReference: 'TX-${attempt.attemptId}', status: status, revision: status == PaymentStatus.succeeded ? 2 : 1, updatedAt: now, allowedActions: { status == PaymentStatus.succeeded ? PaymentAction.viewReceipt : PaymentAction.checkStatus, }, );
Future<PaymentStatusSnapshot?> submit( PaymentAttempt attempt, CheckoutOrder order, ) async { // The fixture records identity before simulating transport. A real host // must persist this durably before sending and deduplicate server-side. submittedIds.add(attempt.attemptId); sentOrder = order; await Future<void>.delayed(delay); return switch (scenario) { CheckoutDemoScenario.lostResponse => null, CheckoutDemoScenario.pendingOffline => snapshot( attempt, PaymentStatus.pending, ), CheckoutDemoScenario.receiptRetry => snapshot( attempt, PaymentStatus.succeeded, ), }; }
Future<PaymentStatusSnapshot> check(PaymentAttempt attempt) async { checkedIds.add(attempt.attemptId); await Future<void>.delayed(delay); if (scenario == CheckoutDemoScenario.pendingOffline && checkedIds.length == 1) { throw StateError('Synthetic offline response'); } return snapshot(attempt, PaymentStatus.succeeded); }
String methodLabel(CheckoutOrder order) { final id = order.selectedMethodId; final method = order.methods.firstWhere( (m) => m.id == id, orElse: () => order.methods.first, ); final tail = method.kind == PaymentMethodKind.virtualAccount ? '8800' : '2190'; return '${method.label} •••• $tail'; }
Future<PaymentReceiptData> receipt(PaymentAttempt attempt) async { receiptLoads++; await Future<void>.delayed(delay); if (scenario == CheckoutDemoScenario.receiptRetry && receiptLoads == 1) { throw StateError('Synthetic receipt service failure'); } return PaymentReceiptData( transactionId: attempt.serverReference!, merchantName: sentOrder!.merchant, paidAt: now, lines: sentOrder!.quote.lines, total: sentOrder!.quote.total, methodLabel: methodLabel(sentOrder!), ); }}
/// Full native phone host shell around the existing copyable D104 block.class CheckoutBlockDemo extends StatefulWidget { const CheckoutBlockDemo({ super.key, this.host, this.initialDark = false, this.quoteFor, }); final CheckoutDemoHost? host; final bool initialDark;
/// Replaces the fixture pricing, e.g. to control answer order in tests. final Future<PaymentQuote> Function(String methodId)? quoteFor;
@override State<CheckoutBlockDemo> createState() => _CheckoutBlockDemoState();}
class _CheckoutBlockDemoState extends State<CheckoutBlockDemo> { late CheckoutDemoHost host = widget.host ?? CheckoutDemoHost(); late bool dark = widget.initialDark; CheckoutDemoLook look = CheckoutDemoLook.invoice; bool reducedMotion = false; int session = 1; int attemptSequence = 0; String email = ''; String selectedMethodId = 'balance'; late PaymentQuote quote = _quoteFor('balance'); bool quoting = false; int quoteRequest = 0;
static const _methods = [ PaymentMethod( id: 'balance', label: 'Saldo Ruang Bayar', kind: PaymentMethodKind.balance, detail: 'Saldo Rp350.000', feeNote: 'Biaya layanan Rp2.500', ), PaymentMethod( id: 'va', label: 'Virtual account', kind: PaymentMethodKind.virtualAccount, detail: 'Bank Demo', feeNote: 'Biaya bank Rp4.000', ), ];
/// Synthetic pricing for the selected method. A real host asks its server; /// the bank transfer carries a higher fee, so the total changes with it. PaymentQuote _quoteFor(String methodId) => PaymentQuote( id: 'QUOTE-DEMO-$session-$methodId', revision: 1, methodId: methodId, lines: [ const QuoteLine(label: 'Paket Belajar', amount: Money.idr(100000)), QuoteLine( label: methodId == 'va' ? 'Biaya bank' : 'Biaya layanan', amount: Money.idr(methodId == 'va' ? 4000 : 2500), kind: QuoteLineKind.fee, ), ], total: Money.idr(methodId == 'va' ? 104000 : 102500), expiresAt: host.now.add(const Duration(minutes: 5)), );
Future<PaymentQuote> _fixtureQuote(String methodId) async { await Future<void>.delayed(host.delay); return _quoteFor(methodId); }
/// Re-quotes for the chosen method. Every request gets a number and a /// session stamp; only the newest answer from the live session may update /// the screen, so a replay or a second tap can never apply a stale price. Future<void> select(PaymentMethod method) async { final request = ++quoteRequest; final current = session; setState(() { selectedMethodId = method.id; quoting = true; }); try { final answer = await (widget.quoteFor ?? _fixtureQuote)(method.id); if (!mounted || current != session || request != quoteRequest) return; setState(() { quoting = false; quote = answer; }); } catch (_) { if (!mounted || current != session || request != quoteRequest) return; // The previous quote stays but belongs to another method, so Pay // remains blocked until a current quote arrives. setState(() => quoting = false); } }
/// Scenario and replay start a fresh session on purpose: the journey /// remounts, quoting state resets and any quote still in flight is stale. void restart([CheckoutDemoScenario? scenario]) => setState(() { host = CheckoutDemoHost( scenario: scenario ?? host.scenario, delay: host.delay, ); session++; email = ''; selectedMethodId = 'balance'; quote = _quoteFor('balance'); quoting = false; quoteRequest++; });
CheckoutOrder get order => CheckoutOrder( merchant: 'Ruang Bayar Akademi · Demo', merchantVerified: true, // Explicitly verified synthetic fixture only. reference: 'INV-DEMO-$session', quote: quote, methods: _methods, selectedMethodId: selectedMethodId, balance: const Money.idr(350000), balanceState: BalanceState.sufficient, receiptEmail: email, quoting: quoting, );
void _onDemoMenu(int value) => switch (value) { 0 => setState(() => look = CheckoutDemoLook.invoice), 1 => setState(() => look = CheckoutDemoLook.wallet), 2 => restart(CheckoutDemoScenario.lostResponse), 3 => restart(CheckoutDemoScenario.pendingOffline), 4 => restart(CheckoutDemoScenario.receiptRetry), 5 => restart(), _ => setState(() => reducedMotion = !reducedMotion), };
static PopupMenuEntry<int> _menuHeader(BuildContext context, String label) => PopupMenuItem<int>( enabled: false, height: 32, child: Text( label, style: Theme.of(context).textTheme.labelSmall?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), );
static PopupMenuEntry<int> _menuItem( int value, String label, { bool selected = false, }) => PopupMenuItem<int>( value: value, child: Row( children: [ Expanded(child: Text(label)), if (selected) const Icon(Icons.check, size: 18), ], ), );
@override Widget build(BuildContext context) { final brand = look == CheckoutDemoLook.wallet ? DemoBrand.soft : DemoBrand.ruangBayar; return MaterialApp( debugShowCheckedModeBanner: false, theme: buildTheme(brand, Brightness.light), darkTheme: buildTheme(brand, Brightness.dark), themeMode: dark ? ThemeMode.dark : ThemeMode.light, themeAnimationDuration: Duration.zero, locale: const Locale('id'), supportedLocales: const [Locale('id'), Locale('en')], localizationsDelegates: const [ PaymentLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], builder: (context, child) { final media = MediaQuery.of(context); // The demo's own switch joins the OS flags; it never clears them. return MediaQuery( data: media.copyWith( disableAnimations: media.disableAnimations || reducedMotion || View.of( context, ).platformDispatcher.accessibilityFeatures.reduceMotion, ), child: child!, ); }, home: Builder( builder: (context) => AnnotatedRegion<SystemUiOverlayStyle>( value: (dark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark) .copyWith( systemNavigationBarColor: Colors.transparent, systemNavigationBarDividerColor: Colors.transparent, systemNavigationBarContrastEnforced: false, ), child: Scaffold( appBar: AppBar( title: const Text('Checkout · Demo'), actions: [ PaymentIconButton( icon: dark ? Icons.light_mode_outlined : Icons.dark_mode_outlined, tooltip: dark ? 'Mode terang' : 'Mode gelap', onPressed: () => setState(() => dark = !dark), ), PopupMenuButton<int>( tooltip: 'Menu demo', onSelected: _onDemoMenu, itemBuilder: (context) => [ _menuHeader(context, 'Tampilan'), _menuItem( 0, 'Invoice', selected: look == CheckoutDemoLook.invoice, ), _menuItem( 1, 'Dompet', selected: look == CheckoutDemoLook.wallet, ), _menuHeader(context, 'Skenario'), _menuItem( 2, 'Respons hilang', selected: host.scenario == CheckoutDemoScenario.lostResponse, ), _menuItem( 3, 'Pending lalu offline', selected: host.scenario == CheckoutDemoScenario.pendingOffline, ), _menuItem( 4, 'Struk gagal dimuat', selected: host.scenario == CheckoutDemoScenario.receiptRetry, ), _menuHeader(context, 'Demo'), _menuItem(5, 'Putar ulang'), _menuItem(6, 'Kurangi gerakan', selected: reducedMotion), ], ), ], ), body: SafeArea( top: false, child: HostCheckoutJourney( key: ValueKey(session), layout: look == CheckoutDemoLook.wallet ? CheckoutLayout.wallet : CheckoutLayout.invoice, order: order, clock: () => host.now, newAttemptId: () => 'DEMO-${++attemptSequence}', onSelectMethod: select, onReceiptEmailChanged: (value) => setState(() => email = value), onSubmit: host.submit, onCheckStatus: host.check, onLoadReceipt: host.receipt, onOtherAction: (_, _) => throw UnsupportedError('No such fixture action'), onDone: restart, // No platform effect is performed or falsely reported as success. onShare: (_) async => ShareOutcome.dismissed, onCopy: (_) async => false, ), ), ), ), ), ); }}Verification and limits
Section titled “Verification and limits”Widget tests cover same-attempt recovery, offline checks without resubmission, receipt retry, quote updates and stale-answer rejection, look switching and reduced motion. The wallet review and receipt-retry action are reachable at 320 dp with 200% text. The host must persist attempts across process restarts. See Compatibility for device coverage.