Dismiss Keyboard On Tapping Outside of Fields

The script includes 2 examples about where you can dismiss keyboard:

  • Dismiss keyboard by tapping on any part of the screen
  • Dismiss keyboard by tapping on this button
import 'package:flutter/material.dart';

class ExamplePage extends StatefulWidget {
  const ExamplePage({Key? key}) : super(key: key);

  _ExamplePageState createState() => _ExamplePageState();

class _ExamplePageState extends State<ExamplePage> {
  TextEditingController _controller = TextEditingController();

  void dispose() {

  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        //Dismiss keyboard by tapping on any part of the screen
        FocusScope.of(context).requestFocus(new FocusNode());
      child: Scaffold(
        body: SafeArea(
          child: Container(
            color: Colors.lightGreen,
            padding: const EdgeInsets.all(16.0),
            width: MediaQuery.of(context).size.width,
            height: 300,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                TextField(controller: _controller),
                ElevatedButton(onPressed: (){
                  //Dismiss keyboard by tapping on this button
                  FocusScope.of(context).requestFocus(new FocusNode());
                }, child: Text('Search'))

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.