Skip to main content

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);

  @override
  _ExamplePageState createState() => _ExamplePageState();
}

class _ExamplePageState extends State {
  TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  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.