Search in a Flutter app

In a Flutter app the SearchService is a bean like any other: a widget gets it, searches at every keystroke, and shows the hits with their matches highlighted. With the navigation starter, a hit's link opens its screen and the app's language picks the index; a shortcut opens the search from anywhere. The search of the site you are reading is built this way.

Why

The index is in memory and built once, so a search answers within a frame or two, offline, in a browser as on a phone. The Flutter starter already has the parts around it: HighlightedText for the matches, ThemeText for results that change the theme's way, shortcuts in the configuration.

Example

# lib/resources/application.yml
spring:
  search:
    collapse-by: page
    markdown:
      - location: resources:content/docs/**/*.md
        exclude: ['**/contents*.md']
        link: /docs/{path}
  flutter:
    shortcuts:
      search.open: [primary+k, slash]
// The results of the query, as the user types.
class SearchPanel extends StatefulWidget {
  const SearchPanel({super.key});

  @override
  State<SearchPanel> createState() => _SearchPanelState();
}

class _SearchPanelState extends State<SearchPanel> {
  var _hits = <SearchHit>[];

  Future<void> _search(String query) async {
    final route = context.route;
    final hits = await context.bean<SearchService>().search(
      query,
      language: route.language,      // the address's language, with the navigation
    );
    if (mounted) setState(() => _hits = hits);
  }

  @override
  Widget build(BuildContext context) => Column(
    children: [
      TextField(autofocus: true, onChanged: _search),
      for (final hit in _hits) _Result(hit),
    ],
  );
}

class _Result extends StatelessWidget {
  const _Result(this.hit);

  final SearchHit hit;

  @override
  Widget build(BuildContext context) {
    final snippet = hit.snippet('body', length: 140);
    return GestureDetector(
      onTap: () => context.route.go(hit.document.link!),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(hit.document.fields['heading'] ?? hit.document.title),
          HighlightedText(
            snippet.text,
            highlights: [
              for (final r in snippet.ranges) TextRange(start: r.start, end: r.end),
            ],
            highlightStyle: TextStyle(color: SpringTheme.of(context).colorScheme.primary),
            maxLines: 2,
          ),
        ],
      ),
    );
  }
}
// ⌘K, Ctrl+K or / opens the search from any screen.
@Component()
class SearchActions {
  @Shortcut('search.open')
  Future<void> open(BuildContext context) => showSearchPanel(context);
}

Notes

See also