Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to Dismiss the Virtual Keyboard in a Flutter App?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 Unfocus 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 unfocus
      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
Last Updated : 05 Aug, 2022
Like Article
Save Article
Similar Reads