How to Close Keyboard in Flutter

The on-screen keyboard significantly impacts the usability of mobile apps. Whether you’re creating forms, search fields, or any text input functionality, ensuring the keyboard closes when necessary is critical for these reasons:

  • Enhanced User Experience: Reduces clutter on the screen when input isn’t required.
  • Prevents UI Overlap: Avoids situations where the keyboard hides critical UI elements.
  • Improved Accessibility: Allows users to navigate the app effortlessly.

Flutter offers several straightforward solutions to implement this feature. Let’s dive into each in detail.

Also Read :- How to Draw a Line in Flutter?


How to Close Keyboard in Flutter

Flutter, being a robust SDK for UI development, provides built-in tools and methods to programmatically control the keyboard. Here’s how you can close the keyboard efficiently:

1. Using FocusScope to Unfocus Widgets

Flutter’s FocusScope class is the most common and straightforward way to dismiss the keyboard. When a widget loses focus, the keyboard will close automatically.
Here’s an example:

import 'package:flutter/material.dart';

class CloseKeyboardExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Close Keyboard Example")),
body: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(decoration: InputDecoration(labelText: "Enter Text")),
SizedBox(height: 20),
Text("Tap anywhere outside the input to close the keyboard"),
],
),
),
),
);
}
}

How It Works

  • GestureDetector detects taps outside the focused widget.
  • FocusScope.of(context).unfocus() removes the focus from the current widget.
  • The keyboard is dismissed automatically.

This approach works universally and doesn’t require additional configurations.

Also Read :- How to Add App Icon in Flutter


2. Implementing SystemChannels.textInput Method

For scenarios requiring lower-level control, Flutter’s SystemChannels.textInput can be used. This method sends a direct signal to the operating system to close the keyboard.

Example:

import 'package:flutter/services.dart';

void closeKeyboard() {
SystemChannels.textInput.invokeMethod('TextInput.hide');
}

Integrate this method with a button or user action to trigger the keyboard dismissal.

Best Use Case

  • Ideal for cases where you want explicit control over the keyboard state.

Also Read :- How to Disable Button in Flutter


3. Combining FocusNode for Precise Control

Using FocusNode is another effective way to manage the keyboard. With FocusNode, you can programmatically focus or unfocus widgets.

Example:

import 'package:flutter/material.dart';

class FocusNodeExample extends StatefulWidget {
@override
_FocusNodeExampleState createState() => _FocusNodeExampleState();
}

class _FocusNodeExampleState extends State<FocusNodeExample> {
FocusNode _focusNode = FocusNode();

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

void closeKeyboard() {
_focusNode.unfocus();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("FocusNode Example")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(focusNode: _focusNode),
ElevatedButton(
onPressed: closeKeyboard,
child: Text("Close Keyboard"),
),
],
),
),
);
}
}

Why Use FocusNode?

  • Provides widget-specific focus control.
  • Useful in forms or multi-input scenarios.

Also Read :- How to Border Container in Flutter?


4. Leveraging Third-Party Packages

Sometimes, packages like keyboard_dismisser simplify implementation. They handle keyboard dismissal logic under the hood.

Installation
Add the dependency to your pubspec.yaml file:

dependencies:
keyboard_dismisser: ^3.0.0

Usage

import 'package:flutter/material.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';

class KeyboardDismisserExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return KeyboardDismisser(
child: Scaffold(
appBar: AppBar(title: Text("Keyboard Dismisser Example")),
body: Column(
children: [
TextField(decoration: InputDecoration(labelText: "Enter Text")),
Text("Tap outside to close the keyboard"),
],
),
),
);
}
}

Advantages

  • Easy integration.
  • Handles dismiss logic automatically.

Also Read :- How to Blur an Image in Flutter


5. Using WillPopScope for Back Button Behavior

In some cases, you may want to dismiss the keyboard when the back button is pressed.

Example:

import 'package:flutter/material.dart';

class WillPopScopeExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Back Button Keyboard Dismissal")),
body: WillPopScope(
onWillPop: () async {
FocusScope.of(context).unfocus();
return true; // Allow navigation
},
child: Column(
children: [
TextField(decoration: InputDecoration(labelText: "Enter Text")),
Text("Press the back button to close the keyboard"),
],
),
),
);
}
}

When to Use

  • Back navigation scenarios.
  • Apps where keyboard dismissal is tightly coupled with user actions.

Also Read :- How to Add Splash Screen in Flutter App


6. Ensuring Compatibility Across Platforms

Flutter’s keyboard handling is generally platform-agnostic. However, you should test the solutions on both Android and iOS to ensure consistency.


Best Practices for Keyboard Management in Flutter

  1. Consistency: Ensure the keyboard behavior aligns with user expectations across all screens.
  2. UI Testing: Test thoroughly for edge cases where the keyboard might interfere with app navigation.
  3. Accessibility: Avoid abrupt dismissals, especially for users relying on assistive technologies.
  4. Error Handling: Provide meaningful error messages when inputs are invalid before closing the keyboard.

Comparison Table: Keyboard Dismissal Methods

Method Use Case Ease of Implementation Platform Support
FocusScope General use Easy Android, iOS
SystemChannels.textInput Explicit control Moderate Android, iOS
FocusNode Form management Moderate Android, iOS
Keyboard Dismisser Auto dismiss logic Easy Android, iOS
WillPopScope Back button handling Moderate Android, iOS

FAQs About Closing Keyboard in Flutter

  1. How do I close the keyboard in Flutter using FocusScope?
    Use FocusScope.of(context).unfocus() to remove focus from the currently active widget.
  2. What is the easiest way to dismiss the keyboard in Flutter?
    Using a GestureDetector combined with FocusScope is the simplest and most effective method.
  3. Can I close the keyboard programmatically in Flutter?
    Yes, methods like SystemChannels.textInput.invokeMethod('TextInput.hide') allow programmatic keyboard dismissal.
  4. Is using third-party packages for keyboard management safe?
    Yes, if the package is well-maintained and widely used, like keyboard_dismisser.
  5. Does Flutter handle keyboard dismissal natively?
    Flutter provides multiple native APIs, such as FocusNode and FocusScope, to manage the keyboard.
  6. Will dismissing the keyboard work on both Android and iOS?
    Yes, all methods mentioned are platform-agnostic.
  7. How can I close the keyboard when navigating to another screen?
    Use FocusScope.of(context).unfocus() before pushing a new route.
  8. Why doesn’t the keyboard close automatically?
    This often happens if the input widget retains focus. Use FocusScope to address this issue.
  9. Can I use Flutter to detect if the keyboard is open?
    Yes, use the MediaQuery property viewInsets to check if the keyboard is visible.
  10. What’s the difference between FocusScope and FocusNode?
    FocusScope manages focus at a higher level, while FocusNode gives you widget-specific control.
  11. How do I prevent the keyboard from covering input fields?
    Use SingleChildScrollView or Scaffold with resizeToAvoidBottomInset.
  12. Can I close the keyboard when a button is clicked?
    Yes, call FocusScope.of(context).unfocus() inside the button’s onPressed method.
  13. Does Flutter handle keyboard dismissal for forms?
    Not automatically; you need to implement focus management manually or use a package.
  14. How can I animate keyboard dismissal?
    Combine FocusScope with animations for a smooth transition.
  15. Is it possible to customize keyboard behavior in Flutter?
    Yes, using TextInputAction and platform-specific configurations.
  16. What happens if I don’t dismiss the keyboard?
    It might obstruct UI elements or confuse users.
  17. Are there any known issues with keyboard dismissal on iOS?
    Rarely, but testing ensures consistent behavior.
  18. How can I test keyboard dismissal during development?
    Use emulators and physical devices to verify functionality.
  19. Can I disable the keyboard temporarily?
    Yes, by setting enabled to false in the TextField.
  20. What tools help debug keyboard issues in Flutter?
    Use the Flutter DevTools and debug logs for insights.
Nishant Sharma
Latest posts by Nishant Sharma (see all)

Leave a Comment