Skip to content
Related Articles

Related Articles

Improve Article

How to Dismiss the Virtual Keyboard in a Flutter App?

  • Last Updated : 22 Sep, 2021

We all have faced situations after filling the text field the virtual keyboard does not go away automatically. We have to click on the back button of our smartphones to remove the virtual keyboard. So in this article, we will see how to dismiss the virtual keyboard in an app with just one tap.

For this, we will be using the onTap() property of the Flutter UI Gesture Detection.

Follow the below steps to implement the above-discussed feature: 

Step1: Use the Gesture detector onTap() property.

Step 2:  Set onTap to unfocus using the unfocus() method.



Example:

Take a look at the below example. Comments have been added to the code for reference.

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
// This is the main application widget.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GFG Unfocous on Tap',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(),
    );
  }
}
  
// This is the homepage
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
// The GestureDetector wraps the homepage
class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        
      // set onTap to unfocous
      onTap: ()=> FocusScope.of(context).unfocus(),
      child: Scaffold(
          
        // Appbar
        appBar: AppBar(title: Text('KeyBoard dismiss Example'),
        centerTitle: true,
        ),
          
        // homepage design
        body: Padding(
           padding: const EdgeInsets.all(16.0),
            
          // Text input
           child:TextField(
           decoration: InputDecoration(
             border: OutlineInputBorder(),
             labelText: 'Enter the text'
           ),
         ),
        ),
      ),
    );
  }
}

Output: 




My Personal Notes arrow_drop_up
Recommended Articles
Page :