Skip to content
Get started
Menu
Get started

Search results

Use this block when someone searches inside a document, scan or other source and opens one of the matches. A result shows a location and an excerpt. Unlike Search field, Find submits a query instead of picking a field value.

From example/, run flutter run -t lib/search_results_demo.dart, or open Find in document in Gallery. Open Find, search for garden, then select page 5. The demo closes the sheet and opens that page. Search for ocean to see no results, or cancel while the demo is scanning. In the standalone demo, choose Gagal mencari sekali in the scenario menu to make the next search fail once. Retry keeps the query.

Copy search_results_block.dart into your app. Put SearchResultsBlock<T> in a bounded page body or a bounded sheet that accepts a caller-owned scrollable. The optional header, form, status and lazy rows share one scroll view, so the header can’t crowd out the field when the keyboard opens. Let the surrounding page or sheet handle the keyboard inset once. The demo omits the modal drag handle so the scroll view can use all the space left above a landscape keyboard. When space is tight, use the keyboard’s Search action from the focused field. Do not wrap the block in another vertical scroll view. Give it a new key when the search scope changes, such as when the host switches to another document.

  • Supply a queryLabel and a search callback. Each submission or retry gets a fresh stream for the trimmed query. An empty query never starts work.
  • Emit cumulative SearchUpdate<T> snapshots, with a progress fraction from 0 to 1 or null if unknown. Do not mutate an emitted list. Reuse it for progress-only updates. Close the stream on success; emit an error on failure.
  • Wire subscription cancellation to your engine or request. The block unsubscribes on Cancel, a different query, or disposal. It discards old matches immediately, even if the engine is still winding down. On retry, the block starts the same query again rather than resuming the failed job.
  • Provide the match’s location, a short display-safe excerpt, and a stable, unique value per hit. Use a page and offset together for multiple hits on one page. The block passes that value to onOpen; the host can close the sheet, then jump to the exact result. The block does not read PDF/OCR data or route anywhere.

The form uses PaymentTextField, PaymentButton and PaymentListItem with the current theme. Search works from the keyboard or the button. Progress and errors have text labels; reduced motion removes the indeterminate animation. The demo includes English and Indonesian controls and synthetic English pages.

Source: compositions/search_results_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';
/// A host match and its display text. Use a stable, unique value per hit.
typedef SearchMatch<T> = ({T value, String title, String excerpt});
/// A cumulative result snapshot. Don't mutate a published list. Progress is
/// null when unknown, or a fraction from 0 to 1.
typedef SearchUpdate<T> = ({List<SearchMatch<T>> matches, double? progress});
/// Start a fresh search for a trimmed query. Close the stream on success or
/// emit an error on failure. Stop the host work on subscription cancellation.
typedef SearchSource<T> = Stream<SearchUpdate<T>> Function(String query);
enum _SearchPhase { idle, running, complete, canceled, failed }
/// A Find form and lazy results in one scroll view. Give it bounded height.
/// The host owns the source, cancellation of its work and opening a match.
/// Key this widget by the search scope (for example, the document ID).
class SearchResultsBlock<T> extends StatefulWidget {
const SearchResultsBlock({
super.key,
required this.queryLabel,
required this.search,
required this.onOpen,
this.header,
});
final String queryLabel;
final SearchSource<T> search;
final ValueChanged<T> onOpen;
/// Scrolls with the form, so it cannot squeeze it out above the keyboard.
final Widget? header;
@override
State<SearchResultsBlock<T>> createState() => _SearchResultsBlockState<T>();
}
class _SearchResultsBlockState<T> extends State<SearchResultsBlock<T>> {
final _queryFocus = FocusNode();
double _keyboardInset = 0;
String _query = '';
_SearchPhase _phase = _SearchPhase.idle;
List<SearchMatch<T>> _matches = [];
double? _progress;
int _generation = 0;
StreamSubscription<SearchUpdate<T>>? _request;
void _detach() {
_generation++;
final request = _request;
_request = null;
// The host handles cleanup errors; the detached search cannot affect UI.
request?.cancel().ignore();
}
void _reset(_SearchPhase phase) {
_phase = phase;
_matches = [];
_progress = null;
}
void _edit(String value) {
final query = value.trim();
if (query == _query) return;
_detach();
setState(() {
_query = query;
_reset(_SearchPhase.idle);
});
}
void _cancel() {
if (_phase != _SearchPhase.running) return;
_detach();
setState(() => _reset(_SearchPhase.canceled));
}
bool get _canSearch => _query.isNotEmpty && _phase != _SearchPhase.running;
void _submit() {
if (!_canSearch) return;
final generation = ++_generation;
setState(() => _reset(_SearchPhase.running));
FocusScope.of(context).unfocus();
bool isCurrent() => mounted && generation == _generation;
void fail() {
if (!isCurrent()) return;
_detach();
setState(() => _reset(_SearchPhase.failed));
}
try {
_request = widget
.search(_query)
.listen(
(update) {
if (!isCurrent()) return;
setState(() {
_matches = update.matches;
_progress = update.progress;
});
},
onError: (Object _, StackTrace _) => fail(),
onDone: () {
if (!isCurrent()) return;
_request = null;
setState(() => _phase = _SearchPhase.complete);
},
);
} catch (_) {
fail();
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final inset = MediaQuery.viewInsetsOf(context).bottom;
final grew = inset > _keyboardInset;
_keyboardInset = inset;
if (grew &&
_queryFocus.hasFocus &&
MediaQuery.sizeOf(context).height - inset <
2 * kMinInteractiveDimension) {
// Flutter reveals the caret with padding that may not fit this viewport.
// Center the focused editor after the framework's caret reveal.
WidgetsBinding.instance.addPostFrameCallback((_) {
final editor = _queryFocus.context;
if (mounted && _queryFocus.hasFocus && editor != null) {
unawaited(Scrollable.ensureVisible(editor, alignment: .5));
}
});
}
}
@override
void dispose() {
_detach();
_queryFocus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final theme = PaymentTheme.of(context);
final type = PaymentType.of(context);
final strings = PaymentLocalizations.of(context);
final group = theme.space(PaymentSpace.group);
final related = theme.space(PaymentSpace.related);
final running = _phase == _SearchPhase.running;
final generation = _generation;
final id = Localizations.localeOf(context).languageCode == 'id';
final searching = id ? 'Mencari…' : 'Searching…';
final canceled = id ? 'Pencarian dibatalkan' : 'Search canceled';
final empty = id ? 'Tidak ada hasil' : 'No results';
final count = _matches.length;
final status = switch (_phase) {
_SearchPhase.running => Padding(
padding: EdgeInsets.symmetric(vertical: group),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: related,
children: [
Semantics(
liveRegion: true,
child: Text(searching, style: type.label),
),
if (_progress != null || !PaymentMotion.of(context).reduced)
LinearProgressIndicator(
value: _progress,
color: theme.accent,
backgroundColor: theme.surfaceMuted,
),
],
),
),
_SearchPhase.failed => StateMessage(
icon: Icons.error_outline,
title: id ? 'Pencarian gagal' : 'Search failed',
message: id
? 'Coba lagi dengan kata kunci yang sama.'
: 'Try again with the same query.',
tone: StatusTone.danger,
actionLabel: strings.retry,
onAction: _submit,
),
_SearchPhase.complete when _matches.isEmpty => Semantics(
liveRegion: true,
label: empty,
child: ExcludeSemantics(
child: StateMessage(icon: Icons.search_off, title: empty),
),
),
_SearchPhase.complete => Padding(
padding: EdgeInsets.only(top: group),
child: Semantics(
liveRegion: true,
child: Text(
id ? '$count hasil' : (count == 1 ? '1 result' : '$count results'),
style: type.caption,
),
),
),
_SearchPhase.canceled => Semantics(
liveRegion: true,
label: canceled,
child: ExcludeSemantics(
child: StateMessage(
icon: Icons.stop_circle_outlined,
title: canceled,
),
),
),
_ => null,
};
return CustomScrollView(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
semanticChildCount: _matches.length,
slivers: [
if (widget.header case final header?) SliverToBoxAdapter(child: header),
SliverPadding(
padding: EdgeInsets.all(group),
sliver: SliverMainAxisGroup(
slivers: [
SliverToBoxAdapter(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: related,
children: [
PaymentTextField(
label: widget.queryLabel,
focusNode: _queryFocus,
type: PaymentTextFieldType.search,
prefixIcon: const PaymentIcon(Icons.search),
onChanged: _edit,
onSubmitted: (_) => _submit(),
),
if (_phase != _SearchPhase.failed)
PaymentButton(
label: running ? strings.cancel : strings.search,
variant: running
? PaymentButtonVariant.secondary
: PaymentButtonVariant.primary,
onPressed: running
? _cancel
: (_canSearch ? _submit : null),
),
],
),
),
if (status != null) SliverToBoxAdapter(child: status),
if (_matches.isNotEmpty)
SliverPadding(
padding: EdgeInsets.only(top: running ? 0 : related),
sliver: SliverList.separated(
itemCount: _matches.length,
separatorBuilder: (_, _) => SizedBox(height: related),
itemBuilder: (_, index) {
final match = _matches[index];
return PaymentListItem(
// A streamed insert must not retarget an in-flight tap.
key: ValueKey((generation, match.value)),
title: match.title,
secondaryTitle: match.excerpt,
onPressed: () {
if (generation == _generation) {
widget.onOpen(match.value);
}
},
);
},
),
),
],
),
),
],
);
}
}
Source: search_results_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/search_results_block.dart';
void main() => runBlockDemo(const SearchResultsDemo());
const _pages = [
'The house stands at the end of a quiet lane.',
'A narrow path leads through the garden to the front door.',
'The front room looks out over the valley.',
'Inside, a stairway leads to the upper floor.',
'The garden wall is built from stone found on the property.',
'The lane continues uphill past a small orchard.',
];
String _text(BuildContext context, String en, String id) =>
Localizations.localeOf(context).languageCode == 'id' ? id : en;
/// A synthetic reader. Find does not depend on a PDF or OCR engine.
class SearchResultsDemo extends StatefulWidget {
const SearchResultsDemo({super.key, this.embedded = false});
final bool embedded;
@override
State<SearchResultsDemo> createState() => _SearchResultsDemoState();
}
class _SearchResultsDemoState extends State<SearchResultsDemo> {
bool _dark = false;
bool _failNextSearch = false;
int _page = 1;
Stream<SearchUpdate<int>> _search(String query, String pageLabel) {
final fail = _failNextSearch;
_failNextSearch = false;
var matches = <SearchMatch<int>>[];
var page = 0;
final needle = query.toLowerCase();
late Timer scan;
late StreamController<SearchUpdate<int>> updates;
updates = StreamController(
onListen: () {
scan = Timer.periodic(const Duration(milliseconds: 300), (timer) {
if (fail) {
timer.cancel();
updates.addError(StateError('Synthetic Find failure'));
unawaited(updates.close());
return;
}
page++;
final excerpt = _pages[page - 1];
if (excerpt.toLowerCase().contains(needle)) {
matches = [
...matches,
(value: page, title: '$pageLabel $page', excerpt: excerpt),
];
}
updates.add((matches: matches, progress: page / _pages.length));
if (page == _pages.length) {
timer.cancel();
unawaited(updates.close());
}
});
},
onCancel: () => scan.cancel(),
);
return updates.stream;
}
Future<void> _find(BuildContext context) async {
final title = _text(context, 'Find in document', 'Cari di dokumen');
final pageLabel = _text(context, 'Page', 'Halaman');
final theme = PaymentTheme.of(context);
final motion = PaymentMotion.of(context);
final match = await showModalBottomSheet<int>(
context: context,
isScrollControlled: true,
useSafeArea: true,
// Fixed route chrome can take all the space above a landscape keyboard.
showDragHandle: false,
backgroundColor: theme.surface,
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: theme.sheetBorderRadius.topLeft,
),
),
sheetAnimationStyle: motion.reduced
? AnimationStyle.noAnimation
: AnimationStyle(
duration: motion.sheetEnter,
reverseDuration: motion.sheetExit,
curve: PaymentMotion.drawer,
),
builder: (context) => Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.viewInsetsOf(context).bottom,
),
child: SizedBox(
height: MediaQuery.sizeOf(context).height * .85,
child: SafeArea(
top: false,
child: SearchResultsBlock<int>(
header: PaymentSheetHeader(
title: title,
onClose: () => Navigator.pop(context),
),
queryLabel: _text(context, 'Search text', 'Teks pencarian'),
search: (query) => _search(query, pageLabel),
onOpen: (page) => Navigator.pop(context, page),
),
),
),
),
);
if (mounted && match != null) setState(() => _page = match);
}
Widget _reader(BuildContext context) {
final type = PaymentType.of(context);
final group = PaymentTheme.of(context).space(PaymentSpace.group);
final page = _text(context, 'Page', 'Halaman');
return ListView(
padding: EdgeInsets.all(group),
children: [
Text(_text(context, 'House tour', 'Tur rumah'), style: type.title),
SizedBox(height: group),
PaymentButton(
label: _text(context, 'Find in document', 'Cari di dokumen'),
variant: PaymentButtonVariant.secondary,
onPressed: () => _find(context),
),
SizedBox(height: group),
Text('$page $_page', style: type.heading),
Text(_pages[_page - 1], style: type.bodyFor(context)),
],
);
}
@override
Widget build(BuildContext context) => widget.embedded
? _reader(context)
: BlockDemoShell(
title: 'Cari · Demo',
dark: _dark,
onToggleDark: () => setState(() => _dark = !_dark),
scenarios: [
(
label: 'Gagal mencari sekali',
onSelected: () => _failNextSearch = true,
),
],
body: _reader,
);
}
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)),
),
),
);
}