Flutter 键盘弹出事件

前言

学习 MDC Flutter 教程 的时候有一个登录页面,一时好奇在 Flutter 中键盘弹出事件怎么监听,经过半天折腾终于找到一个比较完善的解决方案.

解决方案分析

首先我找到了一个方法, WidgetsBindingObserver.didChangeMetrics

该方法能够获取到屏幕的改变(弹出键盘,旋转屏幕),在键盘弹出的一瞬间就会回调该方法,于是在输入框获得焦点的情况下我通过 ScrollController 将 ListView 滑动到最底部.

WidgetsBindingObserver

@override
void didChangeMetrics() {
    super.didChangeMetrics();
    if ((_usernameFocusNode.hasFocus || _passwordFocusNode.hasFocus) &&
        MediaQuery
            .of(context)
            .viewInsets
            .bottom > 50) {
      setState(() {
        _scrollController.animateTo(
          context.size.height - _listKey.currentContext.size.height,
          duration: Duration(
            milliseconds: 300,
          ),
          curve: Curves.decelerate,
        );
      });
    }
}
复制代码

发现没有效果,因为

Any active animation is canceled. If the user is currently scrolling, that action is canceled.

也就是说在键盘弹出动画完成前我们不能调用 ScrollController.animateTo

无动画解决方案

@override
void didChangeMetrics() {
    super.didChangeMetrics();
    if ((_usernameFocusNode.hasFocus || _passwordFocusNode.hasFocus) &&
        MediaQuery
            .of(context)
            .viewInsets
            .bottom > 50) {
      setState(() {
        _scrollController.jumpTo(context.size.height - _listKey.currentContext.size.height);
      });
    }
}
复制代码

有动画解决方案

WidgetsBinding.addPersistentFrameCallback 这个方法能够完美获得每一帧绘制完成的回调,那么我们在该回调下判断上一帧 viewInsets.bottom 的值是否和当前帧的 viewInsets.bottom 相同,如果相同代表键盘动画完成

@override
void didChangeMetrics() {
    _didChangeMetrics = true;
    super.didChangeMetrics();
}

_widgetsBinding.addPersistentFrameCallback((Duration timeStamp) {
    
  if (!_didChangeMetrics) {
    return;
  }

  _preBottomInset = _bottomInset;
  _bottomInset = MediaQuery.of(context).viewInsets.bottom;

  if (_preBottomInset != _bottomInset) {
    WidgetsBinding.instance.scheduleFrame();
    return;
  }

  _didChangeMetrics = false;
  bottomInsertComplete();
});
复制代码

在 bottomInsertComplete 就是键盘完全弹出收回的回调,这时候我们可以通过判断 viewInsets.bottom 的值来判断键盘的状态.

个人写了一个dart包能够简单获取到键盘弹出隐藏事件

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage>
    with WidgetsBindingObserver, BottomInsertObserver {
    @override
    void bottomInsertComplete() {
        final double bottomInsert = MediaQuery.of(context).viewInsets.bottom;
        // 通过判定 bottomInsert 的值来判定键盘的弹出和隐藏
        print(bottomInsert);
    }
    ...
}
复制代码

你可能感兴趣的:(Flutter 键盘弹出事件)