How to hide soft input keyboard on Flutter after clicking outside TextField/anywhere on screen?

In many mobile applications, there’s a common issue where the soft keyboard persists even after the user clicks outside the TextField or anywhere else on the screen. This can be frustrating for users and affect the overall user experience. In this blog post, we’ll explore how to hide the soft keyboard in Flutter after clicking outside the TextField or anywhere on the screen.

The Traditional Approach

For a long time, developers used a specific method to hide the soft keyboard in Flutter. This involved wrapping the whole screen with a GestureDetector and using the onTap method to call the requestFocus method on FocusScope. However, this approach has its limitations and may not work as expected in certain scenarios.


new Scaffold(
   body: new GestureDetector(
      onTap: () {
         FocusScope.of(context).requestFocus(new FocusNode());
      },
      child: new Container(
         //rest of your code write here
      ),
   ),
)

The Updated Approach (May 2021)

With the introduction of Dart 2 and null-safety, a more efficient way to hide the soft keyboard has been discovered. This approach uses FocusManager.instance.primaryFocus?.unfocus() instead of GestureDetector. This method is not only easier to implement but also more reliable in hiding the soft keyboard.


return GestureDetector(
   onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
   child: Scaffold(
      appBar: AppBar(
         title: Text('Login'),
      ),
      body: Body(),
   ),
);

The Most Simplest Solution Yet

Recently, a simpler and more effective way to hide the soft keyboard has been introduced in Flutter. This involves using the onTapOutside method in the TextField widget. When the user taps outside the TextField, this method is called, and you can use it to unfocus the primary focus node.


TextField(
   onTapOutside: (event) {
      print('onTapOutside');
      FocusManager.instance.primaryFocus?.unfocus();
   },
)

Conclusion

In conclusion, hiding the soft keyboard in Flutter after clicking outside the TextField or anywhere on the screen can be achieved through various methods. From wrapping the whole screen with a GestureDetector to using the onTapOutside method in the TextField widget, each approach has its advantages and disadvantages. By understanding these different methods, developers can choose the most suitable solution for their specific use case and provide a better user experience for their mobile application users.