相当于Flutter的SearchAnchor/SearchBar中的onSubmitted回调

xqnpmsa8  于 2023-05-29  发布在  Flutter
关注(0)|答案(1)|浏览(198)

当在Flutter的SearchAnchor/SearchBar小部件中输入搜索词时,按回车键提交搜索是很自然的。不过,对于SearchAnchor/SearchBar,似乎没有与TextField的onSubmitted回调等效的回调。我如何检测到输入键被按下,以便我可以关闭搜索锚点/搜索栏并显示搜索结果?
注意:这个问题是指Flutter 3.10.0中首次发布的SearchBar / SearchAnchor小部件
我已经研究了SearchAnchor/SearchBar API,并尝试了各种方法来发现用户何时点击回车键,如以下代码片段所示:

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 [];
      },
      // No onSubmitted callback.
    );
  }
}
g52tjvyc

g52tjvyc1#

将你的textfield/searchbar/anything-with-text封装在一个RawKeyboardListener小部件中。Docs here
简而言之,你的代码看起来像这样:

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
);

如果你想在按下回车键时关闭文本字段类型的东西并清除文本,请执行以下操作:

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

希望这有帮助!

相关问题