Trending Articles       10 Flutter Listview Examples       Flutter Custom Button Example       Flutter Audio Recording       Flutter 2.0 Autocomplete TextField       Current Location Google Maps

Flutter How to Dismiss Keyboard programmatically

Published May 26, 2021

When we focus on the Textfield in flutter keyboard will come and we can write something, but when we tap outside of the Textfield or TextFormfield widget keyboard will not dismiss. Then how we will dismiss the keyboard when we tap on outside textformfield widgets. Let see how we can hide keyboard on tap on outside by below steps

Let's get started

Step 1: Create Flutter Application

Step 2: Create a widget which contains a Textfield widget.

Step 3: Now we need to find the Tap event of entire window except the current focus TextField widget.

To hanlde tap events we will use GestureDetector widget which we can hanlde tap,drag,hold events.

GestureDetector(
  onTap: () {
  }

 

Fine we have GestureDetector widget, to handle event for the entire window where we need to put this widget, yes we need to put this widget as parent widget in the widget tree.

@override
Widget build(BuildContext context) {
  return MaterialApp(
  home: GestureDetector(
    onTap: () {

    })

);

 

Step 4: Dismiss keyboard

To dismiss keyboard we have to remove the focus of the current TextField. To do this we will use below code

FocusScope.of(context).requestFocus(new FocusNode());

 

Flutter Dismiss Keyboard

 

Complete Example code

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  final _messangerKey = GlobalKey<ScaffoldMessengerState>();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: GestureDetector(
        onTap: () {

          _messangerKey.currentState.showSnackBar(
            SnackBar(
              duration: Duration(milliseconds: 500),
              content: const Text('A SnackBar has been shown.'),
            ),
          );

          FocusScope.of(context).requestFocus(new FocusNode());


        },
        child: Scaffold(
          body: Container(
            child: Center(
              child: TextField(
                decoration: InputDecoration(
                    hintText: ("Enter Name")
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

 

Tags: Keyboard, hide Keyboard, Dismiss Keyboard, Close Keyboard


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

188 Views

Flutter Questions

Android Questions

© 2021 RRTutors . All Rights Reserved.