how to show flutter search textfield without click

Viewed 4136

I'd like to open search page with search textfield focused directly. I don't want to go through another step of clicking search iconbutton to type in the search word. What code do I have to write? Here is my current code. I don't want this to show up ;https://i.stack.imgur.com/bgiRE.png but this to show up when this page opens ;https://i.stack.imgur.com/VzFuz.png

 class Search extends StatefulWidget {
 @override
 _SearchState createState() => _SearchState();
 } 

class _SearchState extends State<Search> {
@override
Widget build(BuildContext context) {
 return Scaffold(
   appBar: AppBar(
    title: Text('Search App'),
    actions: [
      Builder(
        builder: (context) => IconButton(
            icon: Icon(Icons.search),
            onPressed: () async {
              await showSearch(context: context, delegate: DataSearch());
            }),
          )
        ],
       ),
      );
     }
    }

   class DataSearch extends SearchDelegate<String> {
   List allfields = ['a', 'b', ... ];
 
  @override
  List<Widget> buildActions(BuildContext context) {
                     ...
  }

  @override
  Widget buildLeading(BuildContext context) {
                        ...
  }

  @override
  Widget buildResults(BuildContext context) {
                    ...
  }

 @override
 Widget buildSuggestions(BuildContext context) {
                   ...
 }

PS: I solved this problem by not making another page for search. I made a page with search bar on it, and now when I click it, I go directly to the searching state.

2 Answers

Though I did not find any textfield on your code, but assume your demands. Set a autofocus on your text field like below.

TextField(
  autofocus: true,
)

Read more here.

I think you can do something like this,

class _SearchState extends State<Search> {
  @override
  Widget build(BuildContext context) {
    void openSearch() async {
      await showSearch(context: context, delegate: DataSearch(), query: '');
    }

    openSearch();

    return Scaffold(
      appBar: AppBar(
        title: Text('Search App'),
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () { openSearch(); },
          )
        ],
      ),
    );
  }
}

Hope that solves your issue.

Related