What's the problem?
Sometimes, when you type in an app, the keyboard pops up and can cover things on the screen, like buttons at the bottom. This can be annoying because you might want to see these things, or maybe you want to hide them on purpose so they don't get in the way of typing.
The Simple Solution
Flutter gives you a way to know if the keyboard is showing or not without adding any extra libraries or plugins. You can build a special widget that watches for these changes.
How It Works (Without Plugins)
We use something called WidgetsBindingObserver
. This is like a helper that tells your widget when certain things happen in the app's layout, like when the keyboard appears or disappears.
Key Idea
By checking the bottom space used by the screen (viewInsets.bottom
), you can tell if the keyboard is open. If viewInsets.bottom
is greater than 0, it means the keyboard (or other system UI like a navigation bar) is taking up space at the bottom. For keyboards, this value changes.
Building the Listener Widget
We create a StatefulWidget
called KeyboardVisibility
.
Inside its state, we mix in WidgetsBindingObserver
.
Important Steps:
- Start watching (
addObserver
) when the widget starts. - Stop watching (
removeObserver
) when the widget is closed to save resources. - Implement
didChangeMetrics
. This function gets called when the screen layout changes (like the keyboard appearing). - Inside
didChangeMetrics
, we checkMediaQuery.of(context).viewInsets.bottom
. - Based on the value, we know if the keyboard is visible or hidden.
- We then call a function provided to the widget (
onKeyboardStateChanged
) to let the parent widget know the state.
How to Use It
Wrap the part of your app that needs to react to the keyboard state changes with this KeyboardVisibility
widget. You provide a function to onKeyboardStateChanged
that will run whenever the keyboard shows or hides.
Example Code
KeyboardVisibility(
onKeyboardStateChanged: (state) => _handleKeyboardStateChange(state), // Your function
child: YourMainContentWidget(), // The part of your UI that needs watching
)
This makes it easy to show or hide elements, resize layouts, or do anything else you need when the keyboard state changes.