Flutter-更改SearchDelegate的搜索提示文本

Des*_*vic 8 search hint flutter

在的当前实现中SearchDelegate,没有任何选项可以更改提示文本。当查询为空时,搜索屏幕将在查询字段中显示“搜索”作为提示文本。

提示文本当前在第395行中定义如下:

final String searchFieldLabel = MaterialLocalizations.of(context).searchFieldLabel;
Run Code Online (Sandbox Code Playgroud)

但是,已报告该主题存在一个问题

我无法为此提出任何解决方案。您知道该问题的任何解决方法吗?

Raf*_*zan 15

class SongSearch extends SearchDelegate<String> {
  SongSearch({
    String hintText = "Song Search",
  }) : super(
          searchFieldLabel: hintText,
          keyboardType: TextInputType.text,
          textInputAction: TextInputAction.search,
        );
.....
Run Code Online (Sandbox Code Playgroud)


Jor*_*ies 11

通过创建自己的DefaultMaterialLocalizations类并将其传递到MaterialApp小部件中,可以解决此问题:

void main() => runApp(SearchApp());

class SearchApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        CustomLocalizationDelegate(),
      ],
      home: Scaffold(
        appBar: AppBar(
          title: Text('Search demo'),
        ),
        body: Center(
          child: Builder(
            builder: (context) => MaterialButton(
              child: Text('Search'),
              onPressed: () => showSearch(
                context: context,
                delegate: DummyDelegate(),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class DummyDelegate extends SearchDelegate<String> {
  @override
  List<Widget> buildActions(BuildContext context) => [];

  @override
  Widget buildLeading(BuildContext context) => IconButton(
    icon: Icon(Icons.close),
    onPressed: () => Navigator.of(context).pop(),
  );

  @override
  Widget buildResults(BuildContext context) => Text('Result');

  @override
  Widget buildSuggestions(BuildContext context) => Text('Suggestion');
}

class CustomLocalizationDelegate extends LocalizationsDelegate<MaterialLocalizations> {
  const CustomLocalizationDelegate();

  @override
  bool isSupported(Locale locale) => locale.languageCode == 'en';

  @override
  Future<MaterialLocalizations> load(Locale locale) => SynchronousFuture<MaterialLocalizations>(const CustomLocalization());

  @override
  bool shouldReload(CustomLocalizationDelegate old) => false;

  @override
  String toString() => 'CustomLocalization.delegate(en_US)';
}

class CustomLocalization extends DefaultMaterialLocalizations {
  const CustomLocalization();

  @override
  String get searchFieldLabel => "My hint text";
}
Run Code Online (Sandbox Code Playgroud)


Man*_*seh 8

当前,SearchDelegate具有一个可选成员“ searchFieldLabel”,用于指定搜索字段的标签。它看起来应该像这样:

  @override
  String get searchFieldLabel => 'custom label';
Run Code Online (Sandbox Code Playgroud)

  • 应将其检查为正确答案。第一个是当您的应用程序中有两个或多个搜索时该解决方法不起作用。 (7认同)