keyboard_visibility.dart 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import 'dart:ui';
  2. import 'package:flutter/widgets.dart';
  3. class KeyboardVisibilty extends StatefulWidget {
  4. const KeyboardVisibilty({
  5. Key? key,
  6. required this.child,
  7. this.onKeyboardShow,
  8. this.onKeyboardHide,
  9. }) : super(key: key);
  10. final Widget child;
  11. final VoidCallback? onKeyboardShow;
  12. final VoidCallback? onKeyboardHide;
  13. @override
  14. KeyboardVisibiltyState createState() => KeyboardVisibiltyState();
  15. }
  16. class KeyboardVisibiltyState extends State<KeyboardVisibilty>
  17. with WidgetsBindingObserver {
  18. @override
  19. void initState() {
  20. super.initState();
  21. WidgetsBinding.instance.addObserver(this);
  22. }
  23. @override
  24. void dispose() {
  25. WidgetsBinding.instance.removeObserver(this);
  26. super.dispose();
  27. }
  28. @override
  29. void didChangeMetrics() {
  30. final bottomInset = View.of(context).viewInsets.bottom;
  31. if (bottomInset != _lastBottomInset) {
  32. if (bottomInset > 0) {
  33. widget.onKeyboardShow?.call();
  34. } else {
  35. widget.onKeyboardHide?.call();
  36. }
  37. }
  38. _lastBottomInset = bottomInset;
  39. super.didChangeMetrics();
  40. }
  41. var _lastBottomInset = 0.0;
  42. @override
  43. Widget build(BuildContext context) {
  44. return widget.child;
  45. }
  46. }