flutter_keyboard_visibility icon indicating copy to clipboard operation
flutter_keyboard_visibility copied to clipboard

Ease integration of keyboard listener

Open giorgiogross opened this issue 6 years ago • 1 comments

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....;
  }

}

giorgiogross avatar Aug 01 '19 09:08 giorgiogross

This is perfect! Don't see why this shouldn't be included as an option.

idaWHALE avatar Oct 04 '19 21:10 idaWHALE