How to Detect Keyboard Open Close In Flutter?

· 4 min read
How to Detect Keyboard Open Close In Flutter
How to Detect Keyboard Open Close In Flutter

Sometimes the user needs to detect whether Keyboard Open or Close In Flutter so that the user can take action according to that. So in this article, We will learn about How to Detect Keyboard Open Close In Flutter.

How to Detect Keyboard Open Close In Flutter?

The user wants to detect the keyboard open/close basically anywhere in the app/subtree, So how to show/hide the BottomNavigationBar whenever the keyboard is visible.

To check for keyboard visibility, just check for the viewInsets property anywhere in the widget tree. The keyboard is hidden when viewInsets.bottom is equal to zero.

You can check for the viewInsets with MediaQuery like below:

MediaQuery.of(context).viewInsets.bottom

There is also a flutter plugin to notify about keyboard open/close events. Works both on Android and iOS. You can also check https://github.com/adee42/flutter_keyboard_visibility

Code Snippet will look like the below:

import 'package:keyboard_visibility/keyboard_visibility.dart'; 
 @override void initState() {
 super.initState(); 
 KeyboardVisibilityNotification().addNewListener(
 onChange: (bool visible) {
 print(visible); 
},
); 
}

You can use the keyboard_visibility package to do this effectively, I’ve used it and it works like charm.

To install

dependencies:
  keyboard_visibility: ^0.5.2

Import package like a below:

import 'package:keyboard_visibility/keyboard_visibility.dart';

Usage

@protected
void initState() {
  super.initState();

  KeyboardVisibilityNotification().addNewListener(
    onChange: (bool visible) {
      print(visible);
    },
  );
}

KeyboardVisibilityBuilder

If you don’t want to rely on external libs, you can listen for keyboard show/hide events using WidgetsBindingObserver mixin. I prepared a lightweight KeyboardVisibilityBuilder Widget that handles the behavior for you. The usage is quite similar to AnimatedBuilder:

return KeyboardVisibilityBuilder(
  builder: (context, child, isKeyboardVisible) {
    if (isKeyboardVisible) {
      // build layout for visible keyboard
    } else {
      // build layout for invisible keyboard
    }
  },
  child: child, // this widget goes to the builder's child property. Made for better performance.
);

KeyboardVisibilityBuilder implementation:

class KeyboardVisibilityBuilder extends StatefulWidget {
  final Widget child;
  final Widget Function(
    BuildContext context,
    Widget child,
    bool isKeyboardVisible,
  ) builder;

  const KeyboardVisibilityBuilder({
    Key key,
    this.child,
    @required this.builder,
  }) : super(key: key);

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

class _KeyboardVisibilityBuilderState extends State<KeyboardVisibilityBuilder>
    with WidgetsBindingObserver {
  var _isKeyboardVisible = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    final bottomInset = WidgetsBinding.instance.window.viewInsets.bottom;
    final newValue = bottomInset > 0.0;
    if (newValue != _isKeyboardVisible) {
      setState(() {
        _isKeyboardVisible = newValue;
      });
    }
  }

  @override
  Widget build(BuildContext context) => widget.builder(
        context,
        widget.child,
        _isKeyboardVisible,
      );
}

User can also create a Stateful Widget  and  define a bool variable like the below:

bool _keyboardVisible = false;

Then the user needs to define that method in a Build Method like the below code snippet:

@override
Widget build(BuildContext context) {
    _keyboardVisible = MediaQuery.of(context).viewInsets.bottom != 0;
   return child;
}

You can use WidgetsBinding.instance.window.viewInsets.bottom if it’s value greater than 0.0 then the Keyboard is visible

if(WidgetsBinding.instance.window.viewInsets.bottom > 0.0)
{
   //Keyboard is visible.
}
else
{
   //Keyboard is not visible.
]

Conclusion:

In this article, We have been through How to Detect Keyboard Open Close In Flutter.

Keep Learning !!! Keep Fluttering !!!

Still, need Support for Flutter Development? Do let us know.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

4 comments

  1. Thank you for your article. Below is my solution.

    class MyWidgetState extends State with WidgetsBindingObserver {
    Future get keyboardHidden async {
    final check = () => (WidgetsBinding.instance?.window.viewInsets.bottom ?? 0) check());
    }

    @override
    void didChangeMetrics() {
    keyboardHidden.then((value) => value ? FocusManager.instance.primaryFocus?.unfocus() : null);
    }
    }

Leave a Reply