flutter_keyboard_visibility
flutter_keyboard_visibility copied to clipboard
Ease integration of keyboard listener
Hey,
I have a lot of widgets implementing your listener, very useful. I developed a small mixing through which widgets can implement the listener by changing one line, it does the whole registering and disposing for you if you need just a basic listener. I thought I'd share the code, not sure if you want to add this as some kind of convenience but let me know if you want a PR :)
/// Adds keyboard listener functionality to your State
mixin KeyboardListenerMixin<T extends StatefulWidget> on State<T> {
final _keyboardListener = KeyboardVisibilityNotification();
int _keyboardVisibilitySubscriberId;
bool isKeyboardVisible = false;
@override
@mustCallSuper
void initState() {
super.initState();
_keyboardVisibilitySubscriberId = _keyboardListener.addNewListener(
onChange: (bool visible) {
setState(() {
isKeyboardVisible = visible;
});
},
);
// init visibility state
isKeyboardVisible = _keyboardListener.isKeyboardVisible;
}
@override
@mustCallSuper
void dispose() {
_keyboardListener.removeListener(_keyboardVisibilitySubscriberId);
_keyboardListener.dispose();
super.dispose();
}
}
Usage Add the mixin to your widget state where you want the listener.
class YourStatefulWidgetState extends State<YourStatefulWidget> with KeyboardListenerMixin {
@override
Widget build(BuildContext context) {
if (isKeyboardVisible) return ....something for visible keyboard....;
return .....something for hidden keyboard....;
}
}
This is perfect! Don't see why this shouldn't be included as an option.