一尘不染

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

flutter

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

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

final String searchFieldLabel = MaterialLocalizations.of(context).searchFieldLabel;

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

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


阅读 662

收藏
2020-08-13

共1个答案

一尘不染

通过创建自己的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";
}
2020-08-13