Search code snippets, questions, articles...

Dismiss the mobile screen keyboard in Flutter

The mobile screen keyboard is necessary for many users who need to type on their phone or tablet. However, there are times when the keyboard is just in the way and needs to be dismissed. This can be accomplished in Flutter by using the FocusManager.
ElevatedButton(
    onPressed: () {
        // This code will hide the mobile keyboard screen
        FocusManager.instance.primaryFocus?.unfocus();
    },
    child: const Text('Hide Keyboard'),
)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

The above code can be used if you are using Flutter version 2 or above. It is written with null safety that will dismiss the keyboard when executed on mobile devices.

We have created a textbox and a button where the keyboard screen will be seen on focus and when you click on the 'hide keyboard' button the keyboard screen will hide.

The code that can be used to hide the keyboard screen is as below.

FocusManager.instance.primaryFocus?.unfocus();

Full code example

Column(
  children: [
    const TextField(
      autofocus: true,
    ),
    ElevatedButton(
      onPressed: () {
        FocusManager.instance.primaryFocus?.unfocus();
      },
      child: const Text('Hide Keyboard'),
    )
  ],
)

Explanation:

  1. The code example above creates a Column widget with two children: a TextField widget and an ElevatedButton widget. 
  2. The TextField widget is configured to be autofocused, meaning that it will receive focus when the Column widget is first rendered.
  3. The ElevatedButton widget is configured with an onPressed callback that will be called when the button is tapped.
  4. This callback uses the FocusManager to unfocus the primary focus, which will hide the keyboard.
Was this helpful?
0 Comments