In this article I am going to describe how you can detect the visibility of the keyboard using Flutter on both Android and iOS.
First, create a new Flutter project.
Then add the package flutter_keyboard_visibility in the pubspec.yaml this package can be found here: https://pub.dev/packages/flutter_keyboard_visibility
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_keyboard_visibility: ^5.4.1
then run the Pub get to update dependencies.
Next step is to create a function that will listen to the change of keyboard visibility
bool visibleKeyboard = false;
void checkKeyboardVisibility(){
var keyboardVisibilityController = KeyboardVisibilityController();
keyboardVisibilityController.onChange.listen((visible) {
setState(() {
visibleKeyboard = visible;
});
});
}
the boolean key will be updated according to the visibility of the keyboard.
Note that you should write the function under a stateful widget in order to update the state of the boolean, or in a controller if you are using a state manager such as in the GetX package.
then make sure to call the checkKeyboardVisibility function in the initial state function
@override
void initState(){
super.initState();
checkKeyboardVisibility();
}
and that’s all, once you click on a TextField or any text input widget and the keyboard appears, the boolean visibleKeyboard value will be updated.
Watch video for detailed steps
Check the full code on Github
Visit my youtube channel