Search code examples
flutterkeyboardback-button

How to intercept flutter back-button when keyboard is shown


I want to intercept the back-button of the soft keyboard in flutter. So when I want to close the keyboard by pressing the back-button I want an additional function to be called. How can I do that?

Keyboard Back button

enter image description here


Solution

  • you can use the keyboard_visibility package to achieve this.

    Working Example

    the following code displays a SnackBar once the keyboard is dismissed.

    import 'package:flutter/material.dart';
    import 'package:keyboard_visibility/keyboard_visibility.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      GlobalKey<ScaffoldState> _key;
    
      @override
      void initState() {
        super.initState();
        _key = GlobalKey<ScaffoldState>();
        KeyboardVisibilityNotification().addNewListener(
          onHide: () {
            _key.currentState.showSnackBar(
              SnackBar(
                content: Text("Keyboard closed"),
              ),
            );
          },
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            key: _key,
            body: Center(
              child: TextField(),
            ),
          ),
        );
      }
    }
    
    

    enter image description here