Last active
March 7, 2024 15:22
-
-
Save agordeev/dd8582711ed1d777b666e3f57748eba9 to your computer and use it in GitHub Desktop.
Keyboard Avoiding Flutter Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
/// Returns the top of the keyboard. | |
/// Thus, if the keyboard is hidden, it returns the height of the screen. | |
/// Can be used to avoid the keyboard on a screen with text fields. | |
double useKeyboardTop() { | |
return use(const _KeyboardTopHook()); | |
} | |
class _KeyboardTopHook extends Hook<double> { | |
const _KeyboardTopHook(); | |
@override | |
__KeyboardTopHookState createState() => __KeyboardTopHookState(); | |
} | |
class __KeyboardTopHookState extends HookState<double, _KeyboardTopHook> | |
with | |
// ignore: prefer_mixin | |
WidgetsBindingObserver { | |
late double _state; | |
@override | |
void initHook() { | |
super.initHook(); | |
_state = _getKeyboardTop(); | |
WidgetsBinding.instance.addObserver(this); | |
} | |
@override | |
double build(BuildContext context) => _state; | |
@override | |
void dispose() { | |
super.dispose(); | |
WidgetsBinding.instance.removeObserver(this); | |
} | |
@override | |
void didChangeMetrics() { | |
final newState = _getKeyboardTop(); | |
if (newState != _state) { | |
_state = newState; | |
setState(() {}); | |
} | |
super.didChangeMetrics(); | |
} | |
double _getKeyboardTop() { | |
final view = WidgetsBinding.instance.platformDispatcher.views.first; | |
final Size size = view.physicalSize / view.devicePixelRatio; | |
return size.height - | |
EdgeInsets.fromViewPadding(view.viewInsets, view.devicePixelRatio) | |
.bottom; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment