skip to Main Content

When entering a search term in Flutter’s SearchAnchor/SearchBar widget, it’s natural to press the enter key to submit the search. There isn’t an obvious way to listen for this event though. There isn’t a "onSubmitted" callback like TextField has.

So, how can I detect when the enter key was pressed so I can close the SearchAnchor/SearchBar and show the search results?

Note: This question refers to the SearchBar / SearchAnchor widgets first released in Flutter 3.10.0

I’ve examined the SearchAnchor/SearchBar API and experimented with various approaches for discovering when the user taps the enter key, as noted in this code snippet:

import 'package:flutter/material.dart';

class SearchView extends StatefulWidget {
  const SearchView({super.key});

  @override
  State<SearchView> createState() => _SearchViewState();
}

class _SearchViewState extends State<SearchView> {
  final searchController = SearchController();

  @override
  void initState() {
    searchController.addListener(() {
      // Not called when enter key pressed.
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SearchAnchor(
      // No onSubmitted callback parameter.
      searchController: searchController,
      builder: (context, controller) {
        return SearchBar(
          // No onSubmitted callback parameter
          onTap: () => controller.openView(),
          controller: controller,
          onChanged: (text) {
            // Not called when enter key pressed.
          },
        );
      },
      suggestionsBuilder: (context, controller) {
        // Enter character not found in controller.text
        return [];
      },
    );
  }
}

2

Answers


  1. Wrap your textfield/searchbar/anything-with-text in a RawKeyboardListener widget. Docs here.

    In short, your code will look like this:

    RawKeyboardListener(
      focusNode: SAME FOCUS NODE YOUR TEXTFIELD-TYPE THING HAS,
      onKey: (key) {
         if (key.isKeyPressed(LogicalKeyboardKey.enter)) enterPressed(); // <-- do something here on enter key being pressed while in textfield
      },
      child: YOUR CHILD TEXTFIELD-TYPE WIDGET
    );
    

    If you want to close the textfield-type thing on the enter key being pressed and clear the text, do something like this:

    FocusScope.of(context).unfocus(); // closes the keyboard/unfocuses textfield-type widget
    textEditingController.clear(); // clears the text
    

    Hopefully this helps!

    Login or Signup to reply.
  2. There is an isuue and related pull request on Flutter’s repo.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search