Search code examples
searchflutterhint

Flutter - Change search hint text of SearchDelegate


In current implementation of SearchDelegate, there is no option to change the hint text. When the query is empty, search screen is displaying "Search" in the query field as a hint text.

Hint text is currently defined on line 395 as follows:

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

There is, however, an existing issue to this subject reported.

I wasn't able to come up with any solution for this. Do you know any workaround for the issue?


Solution

  • There is a workaround for this by creating your own DefaultMaterialLocalizations class and passing it into the MaterialApp widget:

    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";
    }