Transaction history
Find a payment by reference or status, load more results, and retry a failed page without losing the rows you already have. Unknown stays unknown; a refund is its own lifecycle beside a successful original payment.







Run and try
Section titled “Run and try”From example/:
flutter run -d <device-id> -t lib/history_block_demo.dartOr open Paged history in the example Gallery. Scroll to Muat lagi (Load more) to append a page. In the standalone demo, choose Gagal memuat halaman berikutnya in the scenario menu to fail the next page once and try its retry. Search INV-2047 for the unknown outcome or INV-2044 for a partial refund, even before loading the page that contains it. The demo simulates a paged server with fixtures; it makes no network request or financial operation.
Assemble it in your host
Section titled “Assemble it in your host”Copy merchant_history.dart and paged_block_footer.dart. Give the block a
bounded viewport and pass accumulated records, the active query and filter,
request state, and whether a next page is available. The block uses one lazy
scroll view and never receives a cursor.
Use history_block_demo.dart as the reference for the host side:
- Apply the query and status filter at the server, before paging. Treat the cursor as opaque and scope it to the active query, filter and sort order.
- On a query or filter change, clear the old rows and cursor and start a new request generation. Discard old successes and failures, even if cancellation is supported. Debounce text requests in the host if your service needs it.
- Append rows and advance the cursor only after a successful next page. On
failure, keep the rows and cursor and retry that same page. A null next
cursor after success means there is no Load more action. Give each failure
a distinct
error.attemptwith its display-safeerror.message, even if an immediate retry fails with the same message.
The fixture uses stable, unique record IDs and a nonempty page whenever it returns another cursor. Your data adapter should normalize overlapping or empty intermediate pages if your service can return them. Authorize access on the server and convert transport errors to display-safe copy in the host.
MerchantHistoryDetail composes PaymentSheet, TransactionDetail and a pinned
return button. The demo also supplies an onReport action that opens the
Report a problem sheet for the selected transaction.
Omit the action for read-only inspection. Reporting never changes payment or
refund state. An unknown result never authorizes a new payment.
| UI | Existing library surface |
|---|---|
| Search, status filter and list states | PaymentTextField.search, PaymentTabs, PaymentMenu, StateMessage |
| Lazy rows and next-page action | TransactionListItem, PaymentButton |
| Status and facts | TransactionDetail, StatusHeader, PaymentPropertyList |
| Refund status | RefundSection |
| Detail layout | PaymentSheet, PaymentSheetHeader, PaymentButton |
Read the history contract and status/receipt contract. The pattern explains the rules; this block demonstrates a host screen using them.
Source
Section titled “Source”Source: compositions/merchant_history.dart
Open this file on GitHub. Copy and adapt it in your host app.
import 'package:flutter/material.dart';import 'package:rakit_ui/rakit_ui.dart';
import 'paged_block_footer.dart';
/// Copyable paged history. Give it a bounded viewport and the accumulated rows/// for the active query. The host owns the cursor, loading and safe errors.class MerchantHistory extends StatelessWidget { const MerchantHistory({ super.key, required this.records, required this.query, required this.filter, required this.onQueryChanged, required this.onFilterChanged, required this.onResetFilters, required this.onOpen, required this.hasMore, required this.onRequestPage, this.loading = false, this.error, });
final List<TransactionRecord> records; final String query; final TransactionFilter filter; final ValueChanged<String> onQueryChanged; final ValueChanged<TransactionFilter> onFilterChanged; final VoidCallback onResetFilters; final ValueChanged<TransactionRecord> onOpen; final bool hasMore; final bool loading;
/// Safe display copy and a distinct attempt number for each failed request. final ({String message, int attempt})? error;
/// Requests the next page or retries the failed page without moving its cursor. final VoidCallback onRequestPage;
@override Widget build(BuildContext context) { final theme = PaymentTheme.of(context); final type = PaymentType.of(context); final l10n = PaymentLocalizations.of(context); final filters = TransactionFilter.values; final folded = PaymentType.isLarge(context) && MediaQuery.sizeOf(context).shortestSide < 600; final activeStatus = filter != TransactionFilter.all; final narrowed = query.trim().isNotEmpty || activeStatus; final id = Localizations.localeOf(context).languageCode == 'id'; final loadMore = id ? 'Muat lagi' : 'Load more'; final group = theme.space(PaymentSpace.group); return CustomScrollView( keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, slivers: [ SliverPadding( padding: EdgeInsets.fromLTRB(group, group, group, 0), sliver: SliverToBoxAdapter( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text( id ? 'Riwayat transaksi' : 'Transaction history', style: type.title, ), SizedBox(height: theme.space(PaymentSpace.inline)), Text( id ? 'Cari referensi dan telusuri status pembayaran.' : 'Search by reference and explore payment statuses.', style: type.caption, ), SizedBox(height: group), PaymentTextField.search( query: query, onChanged: onQueryChanged, label: l10n.searchTransactions, hiddenElements: folded ? const {PaymentFieldPart.label} : const {}, actions: [ if (folded) MergeSemantics( child: Semantics( selected: activeStatus, value: l10n.transactionFilterLabel(filter), child: PaymentMenu( entries: [ for (final status in filters) PaymentMenuItem( label: l10n.transactionFilterLabel(status), icon: status == filter ? Icons.check : null, semanticLabel: status == filter ? '${l10n.transactionFilterLabel(status)}, ${l10n.selected}' : null, onSelected: () => onFilterChanged(status), ), ], trigger: (toggle, focus) => PaymentIconButton( focusNode: focus, icon: activeStatus ? Icons.filter_list_alt : Icons.filter_list, tooltip: l10n.filterByStatus, variant: activeStatus ? PaymentIconButtonVariant.accent : PaymentIconButtonVariant.neutral, onPressed: toggle, ), ), ), ), ], ), if (!folded) ...[ SizedBox(height: theme.space(PaymentSpace.related)), PaymentTabs( tabs: [ for (final status in filters) PaymentTab(label: l10n.transactionFilterLabel(status)), ], selectedIndex: filters.indexOf(filter), onSelected: (index) => onFilterChanged(filters[index]), ), ], ], ), ), ), if (records.isEmpty) SliverPadding( padding: EdgeInsets.symmetric(horizontal: group), sliver: SliverToBoxAdapter( child: Semantics( container: true, liveRegion: true, child: switch ((loading, error, narrowed)) { (true, _, _) => const LoadingSkeleton( rows: 4, leading: false, ), (_, (:final message, :final attempt), _) => StateMessage( key: ValueKey(attempt), icon: Icons.cloud_off_outlined, tone: StatusTone.danger, title: l10n.transactionsFailedTitle, message: message, actionLabel: l10n.retry, onAction: onRequestPage, ), (_, _, true) => StateMessage( icon: Icons.search_off, title: l10n.noMatchesTitle, message: l10n.noMatchesMessage, actionLabel: l10n.resetFilters, onAction: onResetFilters, ), _ => StateMessage( icon: Icons.receipt_long_outlined, title: l10n.noTransactionsTitle, message: l10n.noTransactionsMessage, ), }, ), ), ) else SliverPadding( padding: EdgeInsets.symmetric(horizontal: group), sliver: SliverList.separated( itemCount: records.length, separatorBuilder: (_, _) => const PaymentDivider(), itemBuilder: (_, index) { final record = records[index]; return TransactionListItem( key: ValueKey(record.id), record: record, onTap: () => onOpen(record), ); }, ), ), if (hasMore) SliverPadding( padding: EdgeInsets.all(group), sliver: SliverToBoxAdapter( child: PagedBlockFooter( label: error == null ? loadMore : l10n.retry, loading: loading, error: error, onPressed: onRequestPage, ), ), ), SliverToBoxAdapter(child: SizedBox(height: group)), ], ); }}
/// Inspection works for every kit transaction/refund status. Reporting is an/// optional host action and does not cancel or resubmit a payment.class MerchantHistoryDetail extends StatelessWidget { const MerchantHistoryDetail({ super.key, required this.record, required this.onClose, this.onReport, }); final TransactionRecord record; final VoidCallback onClose; final VoidCallback? onReport;
@override Widget build(BuildContext context) { final id = Localizations.localeOf(context).languageCode == 'id'; // This detail has no editor. Keep the keyboard for an overlaid report // from squeezing the detail behind it. return MediaQuery.removeViewInsets( context: context, removeBottom: true, child: PaymentSheet( header: PaymentSheetHeader( title: 'Detail transaksi', subtitle: record.id, ), body: TransactionDetail(record: record), footer: PaymentButtonGroup( direction: Axis.vertical, children: [ if (onReport != null) PaymentButton( label: id ? 'Laporkan masalah' : 'Report a problem', variant: PaymentButtonVariant.quiet, onPressed: onReport, ), PaymentButton( label: 'Kembali ke riwayat', variant: PaymentButtonVariant.secondary, onPressed: onClose, ), ], ), ), ); }}Source: compositions/paged_block_footer.dart
Open this file on GitHub. Copy and adapt it in your host app.
import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:rakit_ui/rakit_ui.dart';
/// The host keeps the active page on failure and supplies a fresh attempt ID.class PagedBlockFooter extends StatefulWidget { const PagedBlockFooter({ super.key, required this.label, required this.loading, required this.error, required this.onPressed, });
final String label; final bool loading; final ({String message, int attempt})? error; final VoidCallback onPressed;
@override State<PagedBlockFooter> createState() => _PagedBlockFooterState();}
class _PagedBlockFooterState extends State<PagedBlockFooter> { @override void didUpdateWidget(PagedBlockFooter oldWidget) { super.didUpdateWidget(oldWidget); final attempt = widget.error?.attempt; if (attempt == null || attempt == oldWidget.error?.attempt) return;
final footer = context.findRenderObject()! as RenderBox; final viewport = RenderAbstractViewport.of(footer); final position = Scrollable.of(context).position; final offset = position.pixels; final top = viewport.getOffsetToReveal(footer, 0).offset; // Don't pull the reader back to the footer if they scrolled away. if (position.isScrollingNotifier.value || top + footer.size.height <= offset || top >= offset + position.viewportDimension) { return; } WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted || widget.error?.attempt != attempt || !footer.attached || position.isScrollingNotifier.value || position.pixels != offset) { return; } // When the message cannot fit with Retry, reveal the button first. position.ensureVisible( footer, alignmentPolicy: footer.size.height > position.viewportDimension ? ScrollPositionAlignmentPolicy.explicit : ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); }); }
@override Widget build(BuildContext context) { final theme = PaymentTheme.of(context); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: theme.space(PaymentSpace.related), children: [ PaymentButton( label: widget.label, variant: PaymentButtonVariant.secondary, busy: widget.loading, onPressed: widget.onPressed, ), if (widget.error case (:final message, :final attempt)) VisibleBlockError( key: ValueKey(attempt), message: message, child: Text( message, style: PaymentType.of( context, ).bodyFor(context).copyWith(color: theme.textSecondary), ), ), ], ); }}
/// A keyed live region whose copy isn't announced while clipped offscreen.class VisibleBlockError extends Semantics { VisibleBlockError({super.key, required String message, required super.child}) : super( container: true, excludeSemantics: true, liveRegion: true, label: message, );
@override RenderSemanticsAnnotations createRenderObject(BuildContext context) => _RenderVisibleErrorSemantics(properties, Directionality.of(context));}
class _RenderVisibleErrorSemantics extends RenderSemanticsAnnotations { _RenderVisibleErrorSemantics( SemanticsProperties properties, TextDirection textDirection, ) : super( properties: properties, textDirection: textDirection, container: true, excludeSemantics: true, );
@override void assembleSemanticsNode( SemanticsNode node, SemanticsConfiguration config, Iterable<SemanticsNode> children, ) { // Flutter computes clipping before assembly. A scroll can supersede the // reveal, so never publish a new label while the node is hidden. if (config.isHidden) { config = config.copy()..liveRegion = false; if (node.label != config.label) config.label = ''; } super.assembleSemanticsNode(node, config, children); }}Source: history_block_demo.dart
Open this file on GitHub. Copy and adapt it in your host app.
import 'dart:async';
import 'package:flutter/material.dart';import 'package:rakit_ui/rakit_ui.dart';
import 'block_demo_shell.dart';import 'compositions/merchant_history.dart';import 'compositions/report_problem_block.dart';
void main() => runBlockDemo(const HistoryBlockDemo());
enum HistoryDemoState { ready, loading, empty, error, nextPageError }
enum _PageRequest { idle, loading, failed }
typedef HistoryPage = ({List<TransactionRecord> records, String? nextCursor});typedef HistoryPageSource = Future<HistoryPage> Function( String query, TransactionFilter filter, String? cursor, );
final _historyFixture = [ for (final (id, amount, method, status, minute) in [ ('INV-2048', 150000, 'QRIS', PaymentStatus.succeeded, 42), ('INV-2047', 320000, 'Transfer', null, 38), ('INV-2046', 210000, 'QRIS', PaymentStatus.pending, 30), ('INV-2045', 95000, 'Saldo', PaymentStatus.failed, 20), ]) TransactionRecord( id: id, title: id, reference: id, amount: Money.idr(amount), createdAt: DateTime(2026, 11, 4, 10, minute), methodLabel: method, status: status, ), TransactionRecord( id: 'INV-2044', title: 'INV-2044', reference: 'INV-2044', amount: const Money.idr(240000), createdAt: DateTime(2026, 11, 3, 15, 10), methodLabel: 'Transfer', status: PaymentStatus.succeeded, refund: const RefundInfo( status: RefundStatus.partial, amount: Money.idr(50000), ), ), for (var i = 0; i < 24; i++) TransactionRecord( id: 'INV-${2043 - i}', title: 'INV-${2043 - i}', reference: 'INV-${2043 - i}', amount: Money.idr(75000 + 5000 * i), createdAt: DateTime(2026, 11, 3).subtract(Duration(days: i)), methodLabel: i.isEven ? 'QRIS' : 'Transfer', status: i % 3 == 0 ? PaymentStatus.failed : PaymentStatus.succeeded, ),];
/// A runnable host with a synthetic cursor source. No network or payment occurs.class HistoryBlockDemo extends StatefulWidget { const HistoryBlockDemo({ super.key, this.initialState = HistoryDemoState.ready, this.initialDark = false, this.embedded = false, this.fetchPage, this.submitReport, this.fixtureDelay = const Duration(milliseconds: 280), }); final HistoryDemoState initialState; final bool initialDark; final bool embedded; final HistoryPageSource? fetchPage; final SubmitProblemReport? submitReport; final Duration fixtureDelay; @override State<HistoryBlockDemo> createState() => _HistoryBlockDemoState();}
class _HistoryBlockDemoState extends State<HistoryBlockDemo> { late HistoryDemoState _mode = widget.initialState; late bool _dark = widget.initialDark; String _query = ''; TransactionFilter _filter = TransactionFilter.all; List<TransactionRecord> _records = []; String? _nextCursor; int _generation = 0; int _failedAttempt = 0; _PageRequest _request = _PageRequest.idle; bool _failNextReport = false; int _cases = 0;
@override void initState() { super.initState(); unawaited(_loadPage()); }
void _restart(String query, TransactionFilter filter) { setState(() { _generation++; _query = query; _filter = filter; _records = []; _nextCursor = null; _request = _PageRequest.idle; }); unawaited(_loadPage()); }
Future<void> _loadPage() async { if (_request == _PageRequest.loading || (_nextCursor == null && _records.isNotEmpty)) { return; } final generation = _generation; final cursor = _nextCursor; setState(() => _request = _PageRequest.loading); if (_mode == HistoryDemoState.loading) return;
try { final page = await (widget.fetchPage ?? _fixturePage)( _query, _filter, cursor, ); // A completed request (including an error) may belong to an old query. if (!mounted || generation != _generation) return; setState(() { _records = [..._records, ...page.records]; _nextCursor = page.nextCursor; _request = _PageRequest.idle; }); } catch (_) { if (!mounted || generation != _generation) return; setState(() { _request = _PageRequest.failed; _failedAttempt++; }); } }
Future<HistoryPage> _fixturePage( String query, TransactionFilter filter, String? cursor, ) async { final mode = _mode; final fail = mode == HistoryDemoState.error || (mode == HistoryDemoState.nextPageError && cursor != null); if (fail) _mode = HistoryDemoState.ready; if (widget.fixtureDelay > Duration.zero) { await Future<void>.delayed(widget.fixtureDelay); } if (fail) throw StateError('Synthetic page failure'); final matching = TransactionRecord.where( mode == HistoryDemoState.empty ? const [] : _historyFixture, query: query, filter: filter, ); // Only the synthetic server interprets the cursor. final start = cursor == null ? 0 : int.parse(cursor); final end = start + 3; return ( records: matching.skip(start).take(3).toList(), nextCursor: end < matching.length ? '$end' : null, ); }
Future<ConfirmedProblemReport> _submitFixtureReport( ReportProblemDraft draft, ) async { final fail = _failNextReport; _failNextReport = false; if (widget.fixtureDelay > Duration.zero) { await Future<void>.delayed(widget.fixtureDelay); } if (fail) throw StateError('Synthetic rejection before creating a case'); return ( draft: draft, caseId: 'CASE-DEMO-${(++_cases).toString().padLeft(4, '0')}', ); }
Widget _block(BuildContext context) => MerchantHistory( records: _records, query: _query, filter: _filter, onQueryChanged: (value) => _restart(value, _filter), onFilterChanged: (value) { if (value != _filter) _restart(_query, value); }, onResetFilters: () => _restart('', TransactionFilter.all), hasMore: _nextCursor != null, loading: _request == _PageRequest.loading, error: _request != _PageRequest.failed ? null : ( attempt: _failedAttempt, message: switch (( Localizations.localeOf(context).languageCode, _nextCursor, )) { ('id', null) => 'Riwayat belum dapat dimuat. Coba lagi.', ('id', _) => 'Halaman berikutnya gagal dimuat. Transaksi sebelumnya tetap tersedia.', (_, null) => 'History couldn’t load. Try again.', _ => 'Couldn’t load the next page. Previous transactions are still available.', }, ), onRequestPage: () => unawaited(_loadPage()), onOpen: (record) => showPaymentSheet<void>( context: context, builder: (context) => MerchantHistoryDetail( record: record, onClose: () => Navigator.pop(context), onReport: () { unawaited( showReportProblem( context, record: record, onSubmit: widget.submitReport ?? _submitFixtureReport, ), ); }, ), ), );
@override Widget build(BuildContext context) => widget.embedded ? _block(context) : BlockDemoShell( title: 'Riwayat · Demo', dark: _dark, onToggleDark: () => setState(() => _dark = !_dark), scenarios: [ for (final (state, label) in [ (HistoryDemoState.ready, 'Data tersedia'), (HistoryDemoState.loading, 'Memuat'), (HistoryDemoState.empty, 'Belum ada transaksi'), (HistoryDemoState.error, 'Gagal memuat riwayat'), ( HistoryDemoState.nextPageError, 'Gagal memuat halaman berikutnya', ), ]) ( label: label, onSelected: () { _mode = state; _restart('', TransactionFilter.all); }, ), ( label: 'Gagal kirim laporan sekali', onSelected: () => _failNextReport = true, ), ], body: _block, );}Source: compositions/report_problem_block.dart
Open this file on GitHub. Copy and adapt it in your host app.
import 'dart:async';
import 'package:flutter/material.dart';import 'package:rakit_ui/rakit_ui.dart';
enum ReportProblemReason { chargedTwice, wrongAmount, notReceived, other }
typedef ReportProblemDraft = ({ String transactionId, String reference, ReportProblemReason reason, String note,});
typedef ConfirmedProblemReport = ({ReportProblemDraft draft, String caseId});
/// Returns the draft the host actually accepted and its nonblank case ID./// Do not relabel an earlier confirmation with an edited draft. Throw if the/// submitted draft cannot be confirmed. The host owns safe retries.typedef SubmitProblemReport = Future<ConfirmedProblemReport> Function(ReportProblemDraft draft);
/// Opens a draft for this transaction. Closing the sheet never submits a/// report or changes the payment. Drafts only live while the sheet is open.Future<void> showReportProblem( BuildContext context, { required TransactionRecord record, required SubmitProblemReport onSubmit,}) async { if (ModalRoute.of(context)?.isCurrent == false) return; await showPaymentFocusView<void>( context, builder: (_) => _ReportProblemSheet(record: record, onSubmit: onSubmit), );}
enum _SendState { idle, sending, failed }
class _ReportProblemSheet extends StatefulWidget { const _ReportProblemSheet({required this.record, required this.onSubmit});
final TransactionRecord record; final SubmitProblemReport onSubmit;
@override State<_ReportProblemSheet> createState() => _ReportProblemSheetState();}
class _ReportProblemSheetState extends State<_ReportProblemSheet> { final _note = TextEditingController(); final _retryMessage = GlobalKey(); ReportProblemReason? _reason; _SendState _state = _SendState.idle; String? _caseId; int _attempt = 0; bool _closeAfterKeyboard = false;
String get _reference => widget.record.reference ?? widget.record.id; bool get _sending => _state == _SendState.sending; String _t(String en, String id) => Localizations.localeOf(context).languageCode == 'id' ? id : en;
@override void dispose() { _note.dispose(); super.dispose(); }
Future<void> _close() async { final route = ModalRoute.of(context); if (_sending || route == null || !route.isCurrent) return; if (_caseId == null && (_reason != null || _note.text.isNotEmpty)) { if (MediaQuery.viewInsetsOf(context).bottom > 0) { // The confirmation sheet does not avoid the keyboard. Wait for the // actual inset change rather than guessing the IME animation time. _closeAfterKeyboard = true; FocusScope.of(context).unfocus(); return; } final discard = await showPaymentConfirmDialog( context, title: _t('Discard this report?', 'Buang laporan ini?'), message: _t( 'Your reason and note will be lost.', 'Alasan dan catatan Anda akan hilang.', ), confirmLabel: _t('Discard', 'Buang'), destructive: true, ); if (!discard || !mounted || !route.isCurrent || _sending) return; } Navigator.pop(context); }
Future<void> _send() async { final reason = _reason; if (reason == null || _sending || _caseId != null || ModalRoute.of(context)?.isCurrent != true) { return; } final draft = ( transactionId: widget.record.id, reference: _reference, reason: reason, note: _note.text, ); FocusScope.of(context).unfocus(); setState(() { _closeAfterKeyboard = false; _attempt++; _state = _SendState.sending; }); String? caseId; try { final confirmed = await widget.onSubmit(draft); if (confirmed.draft == draft) caseId = confirmed.caseId.trim(); } catch (_) { // Host errors may contain private details; only show safe recovery copy. } if (!mounted) return; setState(() { if (caseId != null && caseId.isNotEmpty) { _caseId = caseId; _state = _SendState.idle; } else { _state = _SendState.failed; } }); if (_state == _SendState.failed) { WidgetsBinding.instance.addPostFrameCallback((_) { // On a short screen this banner scrolls with the form. Bring it // into view even when the editor was at the bottom of the viewport. final message = _retryMessage.currentContext; if (message != null) unawaited(Scrollable.ensureVisible(message)); }); } }
@override Widget build(BuildContext context) { final keyboard = MediaQuery.viewInsetsOf(context).bottom; if (_closeAfterKeyboard && keyboard == 0) { WidgetsBinding.instance.addPostFrameCallback((_) { // Send may have canceled the close since this frame was built. if (!mounted || !_closeAfterKeyboard) return; _closeAfterKeyboard = false; unawaited(_close()); }); } return PopScope<void>( // Every dismissal goes through live state, even if Back follows Send // before Flutter rebuilds the footer. canPop: false, onPopInvokedWithResult: (didPop, _) { if (!didPop) unawaited(_close()); }, child: LayoutBuilder( builder: (context, constraints) => _buildSheet( context, constraints.maxHeight - keyboard, keyboard > 0, ), ), ); }
Widget _buildSheet( BuildContext context, double availableHeight, bool keyboardOpen, ) { final l = PaymentLocalizations.of(context); final t = _t; final theme = PaymentTheme.of(context); final compact = availableHeight < 360 || keyboardOpen; // Leave an editing viewport as well as a full-sized button. At smaller // heights the action scrolls with the form instead of taking all the room. final pinAction = availableHeight >= 160; const sheetKey = Key('report-problem-sheet'); if (_caseId case final caseId?) { final title = t('Report sent', 'Laporan terkirim'); final caseLabel = t('Case ID', 'ID kasus'); final header = PaymentSheetHeader( title: title, onClose: () => unawaited(_close()), ); final done = PaymentButton( label: t('Done', 'Selesai'), onPressed: _close, ); return PaymentSheet( key: sheetKey, header: compact ? null : header, footer: pinAction ? done : null, body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (compact) header, Semantics( container: true, liveRegion: true, excludeSemantics: true, label: '$title. $caseLabel: $caseId', child: PaymentPropertyList( items: [ PaymentPropertyListItem(label: caseLabel, valueText: caseId), ], ), ), if (!pinAction) done, ], ), ); }
final header = PaymentSheetHeader( title: t('Report a problem', 'Laporkan masalah'), onClose: _sending ? null : () => unawaited(_close()), ); final error = _state == _SendState.failed ? KeyedSubtree( key: _retryMessage, child: PaymentBanner( key: ValueKey(_attempt), tone: StatusTone.danger, title: t( 'No case ID yet. Try again.', 'Belum ada ID kasus. Coba lagi.', ), announce: !keyboardOpen, ), ) : null; final send = PaymentButton( key: const Key('send-report'), label: t('Send report', 'Kirim laporan'), busyLabel: t('Sending report', 'Mengirim laporan'), busy: _sending, onPressed: _reason == null || _sending ? null : _send, ); return PaymentSheet( key: sheetKey, // Keep the scroll view mounted when both header and footer change. header: SizedBox(child: compact ? null : header), footer: !pinAction ? null : compact ? send : Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, spacing: theme.space(PaymentSpace.related), children: [ ?error, PaymentButtonGroup( direction: Axis.vertical, children: [ send, PaymentButton( key: const Key('report-cancel'), label: l.cancel, variant: PaymentButtonVariant.quiet, onPressed: _sending ? null : _close, ), ], ), ], ), body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: theme.space(PaymentSpace.group), children: [ if (compact) ...[header, ?error], PaymentPropertyList( items: [ PaymentPropertyListItem( label: t('Reference', 'Referensi'), valueText: _reference, ), PaymentPropertyListItem( label: t('Amount', 'Nominal'), value: AmountText(widget.record.amount), ), ], ), PaymentSelect<ReportProblemReason>( label: t('What went wrong?', 'Apa masalahnya?'), value: _reason, onChanged: _sending ? null : (value) => setState(() => _reason = value), options: [ for (final reason in ReportProblemReason.values) PaymentSelectOption( value: reason, label: switch (reason) { ReportProblemReason.chargedTwice => t( 'Charged twice', 'Terdebit dua kali', ), ReportProblemReason.wrongAmount => t( 'Wrong amount', 'Nominal salah', ), ReportProblemReason.notReceived => t( "Didn't get what I paid for", 'Pesanan tidak diterima', ), ReportProblemReason.other => t('Something else', 'Lainnya'), }, ), ], ), PaymentTextArea( key: const ValueKey('report-note'), label: t( 'Describe the problem (optional)', 'Jelaskan masalahnya (opsional)', ), description: t( "Don't include your PIN, OTP or card number.", 'Jangan tulis PIN, OTP, atau nomor kartu.', ), controller: _note, minLines: compact ? 1 : 3, maxLength: 500, enabled: !_sending, ), if (!pinAction) send, ], ), ); }}Source: block_demo_shell.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 'themes.dart';
/// Starts a block demo edge-to-edge, as the shipped checkout demo does.void runBlockDemo(Widget app) { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); runApp(app);}
/// The example host's clipboard effect. It reports the real outcome and never/// claims a copy that did not happen. The kit itself never touches the/// clipboard (B11).Future<bool> copyToClipboard(String value) async { try { await Clipboard.setData(ClipboardData(text: value)); return true; } on PlatformException { return false; }}
/// One developer scenario in the demo menu. Choosing it restarts the/// synthetic session; it is never an end-user action.typedef DemoScenario = ({String label, VoidCallback onSelected});
/// Ordinary phone host chrome shared by the block demos: app themes, Indonesian/// localization, D85 system-bar styling, a light/dark switch and a developer/// scenario menu. It is example scaffolding, not a block runtime: copy the/// composition under `compositions/` and keep your own app shell.class BlockDemoShell extends StatelessWidget { const BlockDemoShell({ super.key, required this.title, required this.dark, required this.onToggleDark, required this.body, this.scenarios = const [], this.lightTheme, this.darkTheme, this.locale = const Locale('id'), this.textScale, });
final String title; final bool dark; final VoidCallback onToggleDark; final List<DemoScenario> scenarios;
/// Optional illustrative host themes; the payment demos use Ruang Bayar. final ThemeData? lightTheme; final ThemeData? darkTheme;
/// Host locale for this synthetic demo. final Locale locale;
/// Optional fixed text scale for accessibility captures; null follows the /// device setting. final double? textScale;
/// Built below the Scaffold, so sheets and toasts find their ancestors. final WidgetBuilder body;
@override Widget build(BuildContext context) => MaterialApp( debugShowCheckedModeBanner: false, theme: lightTheme ?? buildTheme(DemoBrand.ruangBayar, Brightness.light), darkTheme: darkTheme ?? buildTheme(DemoBrand.ruangBayar, Brightness.dark), themeMode: dark ? ThemeMode.dark : ThemeMode.light, locale: locale, supportedLocales: const [Locale('id'), Locale('en')], localizationsDelegates: const [ PaymentLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], builder: (context, child) { final scale = textScale; if (scale == null) return child!; return MediaQuery( data: MediaQuery.of( context, ).copyWith(textScaler: TextScaler.linear(scale)), child: child!, ); }, home: AnnotatedRegion<SystemUiOverlayStyle>( // D85: the host styles the system bars from its resolved theme. value: (dark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark) .copyWith( systemNavigationBarColor: Colors.transparent, systemNavigationBarDividerColor: Colors.transparent, systemNavigationBarContrastEnforced: false, ), child: Scaffold( appBar: AppBar( title: Text(title), actions: [ PaymentIconButton( icon: dark ? Icons.light_mode_outlined : Icons.dark_mode_outlined, tooltip: dark ? 'Mode terang' : 'Mode gelap', onPressed: onToggleDark, ), if (scenarios.isNotEmpty) PopupMenuButton<int>( tooltip: 'Skenario demo', onSelected: (i) => scenarios[i].onSelected(), itemBuilder: (_) => [ for (final (i, s) in scenarios.indexed) PopupMenuItem(value: i, child: Text(s.label)), ], ), ], ), body: SafeArea(top: false, child: Builder(builder: body)), ), ), );}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), ), ), );}Proof and limits
Section titled “Proof and limits”Widget tests cover paging, failed-page retry, stale replies, search, unknown inspection, separate refunds and reachable controls at 320 dp with 200% text. The Android example exercises the paging flow with the synthetic host, not a live server. See Compatibility for device coverage.