Open In App

How to Hide the Keyboard When User Tap Out of the TextField in Flutter?

Improve
Improve
Like Article
Like
Save
Share
Report

Flutter is a UI toolkit developed by Google. It is being utilized by big tech companies like Alibaba, Airbnb, and Google itself to build apps that serve billions of users around the globe. This article will show how to make Rounded Buttons in Flutter. A sample video is given below to get an idea about what we are going to do in this article.

Approach

We will use a focusNode for the TextField, wrap the screen inside the GestureDetector Widget, and listen for the onTap event. When the user taps anywhere on the screen, we will remove the focus from the focusNode of the TextField using the unfocus function of the focusNode.

Syntax

GestureDetector(
    onTap: () {
        _focusNode.unfocus();
    },
    child: Container(
        // Contains the TextField

    ),
);

Implementation

This example Illustrates how to hide the keyboard when the user taps out of the text field in Flutter.

Dart




import 'package:flutter/material.dart';
  
void main() => runApp(const MyApp());
  
class MyApp extends StatelessWidget {
    const MyApp({Key? key}) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            title: 'GFG Hide Keyboard',
            home: Scaffold(
                appBar: AppBar(
                    backgroundColor: Colors.green,
                    title: const Text('GeeksforGeeks - Hide Keyboard Example'),
                ),
                body: const HideKeyboardDemo(),
            ),
        );
    }
}
  
class HideKeyboardDemo extends StatefulWidget {
    const HideKeyboardDemo({Key? key}) : super(key: key);
  
    @override
    _HideKeyboardDemoState createState() => _HideKeyboardDemoState();
}
  
class _HideKeyboardDemoState extends State<HideKeyboardDemo> {
    final _focusNode = FocusNode();
  
    @override
    Widget build(BuildContext context) {
        return GestureDetector(
            onTap: () {
                _focusNode.unfocus();
            },
            child: Container(
                color: Colors.green.shade50,
                child: Center(
                    child: Padding(
                        padding: const EdgeInsets.all(32.0),
                        child: TextField(
                            focusNode: _focusNode,
                            decoration: const InputDecoration(
                                labelText: 'Enter text',
                                border: OutlineInputBorder(),
                            ),
                        ),
                    ),
                ),
            ),
        );
    }
}


Output:



Last Updated : 05 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads