> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Hits Searcher

> Manages search sessions and requests.

export const SearchRequest = () => <Tooltip tip="A search request is a single HTTP call to the Algolia Search API that can run one or more search operations. It can include multiple queries, for example, when querying several indices at once.">
    search request
  </Tooltip>;

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </Tooltip>;

export const Index = () => <Tooltip tip="An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.">
    index
  </Tooltip>;

export const Facet = () => <Tooltip tip="An attribute in your records that lets users filter or group results (for example, by color, brand, or price)." cta="Faceting" href="/doc/guides/managing-results/refine-results/faceting">
    facet
  </Tooltip>;

export const Events = () => <Tooltip tip="An event is a specific action a user takes in your app or on your website." cta="Events" href="/doc/guides/sending-events">
    events
  </Tooltip>;

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="m6 9 6 6 6-6" />
          </svg>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="flutter"
    baseHref="/doc/api-reference/widgets/instantsearch"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
{ value: "vue", label: "Vue", description: "Vue InstantSearch" },
{ value: "ios", label: "iOS", description: "InstantSearch iOS" },
{ value: "android", label: "Android", description: "InstantSearch Android" },
{ value: "flutter", label: "Flutter", description: "Algolia for Flutter" },
]}
  />
</div>

```dart Signature theme={"system"}
HitsSearcher(
  String applicationID,
  String apiKey,
  String indexName,
  // Optional parameters
  bool disjunctiveFacetingEnabled,
  Duration debounce,
)

HitsSearcher.create(
  String applicationID,
  String apiKey,
  SearchState state,
  // Optional parameters
  bool disjunctiveFacetingEnabled,
  Duration debounce,
)

FacetSearcher(
  String applicationID,
  String apiKey,
  String indexName,
  String facet,
  // Optional parameters
  Duration debounce,
)

FacetSearcher.create(
  String applicationID,
  String apiKey,
  FacetSearchState state,
  // Optional parameters
 Duration debounce,
)

MultiSearcher(
  String applicationID,
  String apiKey,
  // Optional parameters
  EventTracker eventTracker
)
```

<Card title="View live demo" icon="monitor-play" href="https://algolia-flutter-showcase.netlify.app/#/?path=hitssearcher%2Fsearch-box-%26-hits-list">
  Open the live Hits Searcher example in your browser.
</Card>

## About this widget

The component handling a <SearchRequest />,
`HitsSearcher` has the following behavior:

* Distinct state changes (including initial state) will trigger a search operation
* State changes are debounced
* On a new search request, any previous ongoing search calls will be cancelled

Algolia for Flutter comes with these searchers:

* `HitsSearcher`. Searches a single <Index />.
* `FacetSearcher`. Searches for <Facet /> values.
* `MultiSearcher`. Aggregates the hits and facet searchers. This is useful for building a federated search, or query suggestions.

## Examples

1. Create a `HitsSearcher`
2. Update search state with [`query`](#param-query) and [`applyState`](/doc/api-reference/widgets/instantsearch/flutter#param-apply-state)
3. Listen to search [`responses`](#param-responses) and build the UI
4. [`dispose`](#param-dispose) of underlying resources

```dart Dart icon=code theme={"system"}
class SearchScreen extends StatefulWidget {
  const SearchScreen({super.key});

  @override
  State<SearchScreen> createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  // 1. Create a Hits Searcher
  final hitsSearcher = HitsSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
  );

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          // 2. Run your search operations
          title: TextField(
            onChanged: (input) => hitsSearcher.query(input),
            decoration: const InputDecoration(
              hintText: 'Search...',
              prefixIcon: Icon(Icons.search),
              fillColor: Colors.white,
              filled: true,
            ),
          ),
        ),
        // 3.1 Listen to search responses
        body: StreamBuilder<SearchResponse>(
          stream: hitsSearcher.responses,
          builder: (_, snapshot) {
            if (snapshot.hasData) {
              final response = snapshot.data;
              final hits = response?.hits.toList() ?? [];
              // 3.2 Display your search hits
              return ListView.builder(
                itemCount: hits.length,
                itemBuilder: (_, i) => ListTile(title: Text(hits[i]['title'])),
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          },
        ),
      );

  @override
  void dispose() {
    super.dispose();
    // 4. Release underling resources
    hitsSearcher.dispose();
  }
}
```

## HitsSearcher

<ParamField body="applicationID" type="String" required>
  The ID of your application.

  ```dart Dart icon=code theme={"system"}
  final hitsSearcher = HitsSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
  );
  ```
</ParamField>

<ParamField body="apiKey" type="String" required>
  Your application's [Search-only API key](/doc/guides/security/api-keys#search-only-api-key).

  ```dart Dart icon=code theme={"system"}
  final hitsSearcher = HitsSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
  );
  ```
</ParamField>

<ParamField body="indexName" type="String" required>
  The index to search into.

  ```dart Dart icon=code theme={"system"}
  final hitsSearcher = HitsSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
  );
  ```
</ParamField>

<ParamField body="state" type="SearchState" required>
  Initial search state.

  ```dart Dart icon=code theme={"system"}
  final hitsSearcher = HitsSearcher.create(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    state: const SearchState(indexName: 'YourIndexName'),
  );
  ```
</ParamField>

<ParamField body="disjunctiveFacetingEnabled" type="bool" default={true}>
  Whether disjunctive faceting is enabled.

  ```dart Dart icon=code theme={"system"}
  final hitsSearcher = HitsSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
    disjunctiveFacetingEnabled: true,
  );
  ```
</ParamField>

<ParamField body="debounce" type="Duration" post={["default: Duration(milliseconds: 100)"]}>
  Search operation debounce duration.

  ```dart Dart icon=code theme={"system"}
  final hitsSearcher = HitsSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
    debounce: const Duration(milliseconds: 100),
  );
  ```
</ParamField>

### Fields

<ParamField body="responses" type="Stream<SearchResponse>">
  Stream of search responses.

  ```dart Dart icon=code theme={"system"}
  StreamBuilder<SearchResponse>(
    stream: hitsSearcher.responses,
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        final response = snapshot.data!;
        return Column(
          children: [
            Text('${response.nbHits} hits found'),
            ListView.builder(
              itemCount: response.hits.length,
              itemBuilder: (context, index) {
                final hit = response.hits[index];
                return ListTile(title: Text(hit['name']));
              },
            ),
          ],
        );
      } else {
        return const CircularProgressIndicator();
      }
    },
  );
  ```
</ParamField>

<ParamField body="state" type="Stream<SearchState>">
  Stream of search states.

  ```dart Dart icon=code theme={"system"}
  StreamBuilder<SearchState>(
    stream: searcher.state,
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        final query = snapshot.data?.query ?? '';
        return Text('Query: $query');
      } else {
        return const CircularProgressIndicator();
      }
    },
  );
  ```
</ParamField>

<ParamField body="eventTracker" type="HitsEventTracker">
  Instance responsible for handling and sending user <Events /> related to search interactions,
  such as clicks, conversions, and views.
  These events help to personalize the user's search experience by providing insights into user behavior.
  `eventTracker` is automatically integrated with the `HitsSearcher` to track events when users interact with the search results.

  ```dart Dart icon=code theme={"system"}
  hitsSearcher.eventTracker.clickedObjects(
    indexName: 'YourIndexName',
    objectIDs: ['objectID1', 'objectID2'],
    eventName: 'your_event_name',
  );
  ```
</ParamField>

### Methods

<ParamField body="query">
  Triggers a search operation with given <SearchQuery />.

  ```dart Dart icon=code theme={"system"}
  hitsSearcher.query('book');
  ```
</ParamField>

<ParamField body="applyState">
  Applies a search state configuration and triggers a search operation.

  ```dart Dart icon=code theme={"system"}
  hitsSearcher.applyState((state) => state.copyWith(query: 'book', page: 0));
  ```
</ParamField>

<ParamField body="snapshot">
  Gets the latest `SearchResponse` value submitted by [`responses`](#param-responses) stream:

  ```dart Dart icon=code theme={"system"}
  final response = hitsSearcher.snapshot();
  ```
</ParamField>

<ParamField body="dispose">
  Releases all underlying resources

  ```dart Dart icon=code theme={"system"}
  hitsSearcher.dispose();
  ```
</ParamField>

## FacetSearcher

<ParamField body="applicationID" type="String" required>
  The ID of your application.

  ```dart Dart icon=code theme={"system"}
  final facetSearcher = FacetSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
    facet: 'facet_attribute',
  );
  ```
</ParamField>

<ParamField body="apiKey" type="String" required>
  Your application's [Search-only API key](/doc/guides/security/api-keys#search-only-api-key).

  ```dart Dart icon=code theme={"system"}
   final facetSearcher = FacetSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
    facet: 'facet_attribute',
  );
  ```
</ParamField>

<ParamField body="indexName" type="String" required>
  The index to search into.

  ```dart Dart icon=code theme={"system"}
  final facetSearcher = FacetSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
    facet: 'facet_attribute',
  );
  ```
</ParamField>

<ParamField body="facet" type="String" required>
  The facet name to search into when doing search for facet values.

  ```dart Dart icon=code theme={"system"}
  final facetSearcher = FacetSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
    facet: 'facet_attribute',
  );
  ```
</ParamField>

<ParamField body="state" type="FacetSearchState" required>
  Initial facet search state.

  ```dart Dart icon=code theme={"system"}
  final facetSearcher = FacetSearcher.create(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    state: FacetSearchState(
      searchState: SearchState(indexName: 'YourIndexName'),
      facet: 'facet_attribute',
    ),
  );
  ```
</ParamField>

<ParamField body="debounce" type="Duration" post={["default: Duration(milliseconds: 100)"]}>
  Search operation debounce duration.

  ```dart Dart icon=code theme={"system"}
  final facetSearcher = FacetSearcher(
    applicationID: 'YourApplicationID',
    apiKey: 'YourSearchOnlyApiKey',
    indexName: 'YourIndexName',
    facet: 'facet_attribute',
    debounce: const Duration(milliseconds: 100),
  );
  ```
</ParamField>

### Fields

<ParamField body="responses" type="Stream<FacetSearchResponse>">
  Stream of search responses.

  ```dart Dart icon=code theme={"system"}
  StreamBuilder<FacetSearchResponse>(
    stream: facetSearcher.responses,
    builder: (BuildContext context,
        AsyncSnapshot<FacetSearchResponse> snapshot) {
      if (snapshot.hasData) {
        final response = snapshot.data;
        final facets = response?.facetHits.toList() ?? [];
        return ListView.builder(
          itemCount: facets.length,
          itemBuilder: (BuildContext context, int index) {
            final facet = facets[index];
            return ListTile(
              title: Text(facet.value)
            );
          },
        );
      } else {
        return const CircularProgressIndicator();
      }
    },
  )
  ```
</ParamField>

<ParamField body="state" type="Stream<FacetSearchState>">
  Stream of facet search states

  ```dart Dart icon=code theme={"system"}
  StreamBuilder<FacetSearchState>(
    stream: searcher.state,
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        final query = snapshot.data?.facetQuery ?? '';
        return Text('Facet query: $query');
      } else {
        return const CircularProgressIndicator();
      }
    },
  );
  ```
</ParamField>

### Methods

<ParamField body="query">
  Triggers a search operation with given search query

  ```dart Dart icon=code theme={"system"}
  facetSearcher.query('book');
  ```
</ParamField>

<ParamField body="applyState">
  Applies a search state configuration and triggers a search operation

  ```dart Dart icon=code theme={"system"}
  facetSearcher.applyState((state) => state.copyWith(facetQuery: 'book'));
  ```
</ParamField>

<ParamField body="snapshot">
  Gets the latest `FacetSearchResponse` value submitted by [`responses`](#param-responses-1) stream:

  ```dart Dart icon=code theme={"system"}
  final response = facetSearcher.snapshot();
  ```
</ParamField>

<ParamField body="dispose">
  Releases all underlying resources

  ```dart Dart icon=code theme={"system"}
  facetSearcher.dispose();
  ```
</ParamField>

## MultiSearcher

<ParamField body="strategy" type="MultipleQueriesStrategy" post={["default: None"]}>
  `MultiSearcher` lets you simultaneously search for hits and facet values in different indices of the same Algolia application.
  It instantiates and manages `HitsSearcher` and `FacetSearcher` instances. Once created, these searchers behave like their independently instantiated counterparts.

  ```dart Dart icon=code theme={"system"}
  final multiSearcher = MultiSearcher(
      applicationID = ApplicationID("YourApplicationID"),
      apiKey = APIKey("YourSearchOnlyApiKey"),
      eventTracker: Insights('MY_APPLICATION_ID', 'MY_API_KEY'),
  )
  ```
</ParamField>

### Methods

<ParamField body="dispose">
  Releases all underlying resources

  ```dart Dart icon=code theme={"system"}
  multiSearcher.dispose();
  ```
</ParamField>

<ParamField body="addHitsSearcher">
  Adds a new `HitsSearcher` to the multi-searcher.

  ```dart Dart icon=code theme={"system"}
  final hitsSearcher = multiSearcher.addHitsSearcher(
    initialState: const SearchState(
      indexName: 'instant_search',
    ),
  );
  ```
</ParamField>

<ParamField body="addFacetSearcher">
  Adds a new `FacetSearcher` to the multi-searcher.

  ```dart Dart icon=code theme={"system"}
  final facetSearcher = multiSearcher.addFacetSearcher(
      initialState: const FacetSearchState(
        facet: 'brand',
        searchState: SearchState(
          indexName: 'instant_search',
        ),
      )
  );
  ```
</ParamField>
