How to Dismiss the Virtual Keyboard in a Flutter App?
Last Updated :
05 Aug, 2022
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());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'GFG Unfocus on Tap' ,
theme: ThemeData(
primarySwatch: Colors.green,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: ()=> FocusScope.of(context).unfocus(),
child: Scaffold(
appBar: AppBar(title: Text( 'KeyBoard dismiss Example' ),
centerTitle: true ,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child:TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter the text'
),
),
),
),
);
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...