flutterdartsearchbar

How can I show the keyboard when clicking in a Flutter Searchbar?


In an Android Flutter/Dart app, I have a SearchBar at the top of the screen. If the user clicks in the SearchBar, the keyboard shows. If the user then dismisses the keyboard (with the down arrow on the keyboard), then clicks back in the SearchBar, the keyboard is not displayed again. How can I force the keyboard to be shown when the user clicks in the SearchBar after having previously dismissed the keyboard?

I have Googled this, and tried many of the FocusNode-based solutions, but nothing has worked. Thanks for any suggestions!


Solution

  • Here's your solution.

    So, this is the output of the below-mentioned source code: View

    Source code:

    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key});
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SafeArea(
            child: Column(
              children: <Widget>[
                TextField(
                  decoration: const InputDecoration(hintText: "Search"),
                  onTap: showKeyboard,
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: ElevatedButton(
                        onPressed: showKeyboard,
                        child: const Text("Show Keyboard"),
                      ),
                    ),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: hideKeyboard,
                        child: const Text("Hide Keyboard"),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      }
    
      Future<void> showKeyboard() async {
        await SystemChannels.textInput.invokeMethod("TextInput.show");
        return Future<void>.value();
      }
    
      Future<void> hideKeyboard() async {
        await SystemChannels.textInput.invokeMethod("TextInput.hide");
        return Future<void>.value();
      }
    }
    

    Note: import import "package:flutter/services.dart"; to use SystemChannels class.