showSearch<T> function

Future<T?> showSearch<T>(
  1. {required BuildContext context,
  2. required SearchDelegate<T> delegate,
  3. String? query = '',
  4. bool useRootNavigator = false}
)

Shows a full screen search page and returns the search result selected by the user when the page is closed.

The search page consists of an app bar with a search field and a body which can either show suggested search queries or the search results.

The appearance of the search page is determined by the provided delegate. The initial query string is given by query, which defaults to the empty string. When query is set to null, delegate.query will be used as the initial query.

This method returns the selected search result, which can be set in the SearchDelegate.close call. If the search page is closed with the system back button, it returns null.

A given SearchDelegate can only be associated with one active showSearch call. Call SearchDelegate.close before re-using the same delegate instance for another showSearch call.

The useRootNavigator argument is used to determine whether to push the search page to the Navigator furthest from or nearest to the given context. By default, useRootNavigator is false and the search page route created by this method is pushed to the nearest navigator to the given context. It can not be null.

The transition to the search page triggered by this method looks best if the screen triggering the transition contains an AppBar at the top and the transition is called from an IconButton that's part of AppBar.actions. The animation provided by SearchDelegate.transitionAnimation can be used to trigger additional animations in the underlying page while the search page fades in or out. This is commonly used to animate an AnimatedIcon in the AppBar.leading position e.g. from the hamburger menu to the back arrow used to exit the search page.

Handling emojis and other complex characters

It's important to always use characters when dealing with user input text that may contain complex characters. This will ensure that extended grapheme clusters and surrogate pairs are treated as single characters, as they appear to the user.

For example, when finding the length of some user input, use string.characters.length. Do NOT use string.length or even string.runes.length. For the complex character "👨‍👩‍👦", this appears to the user as a single character, and string.characters.length intuitively returns 1. On the other hand, string.length returns 8, and string.runes.length returns 5!

See also:

Implementation

Future<T?> showSearch<T>({
  required BuildContext context,
  required SearchDelegate<T> delegate,
  String? query = '',
  bool useRootNavigator = false,
}) {
  delegate.query = query ?? delegate.query;
  delegate._currentBody = _SearchBody.suggestions;
  return Navigator.of(context, rootNavigator: useRootNavigator).push(_SearchPageRoute<T>(
    delegate: delegate,
  ));
}