flutter 定位widget位置、监听键盘弹出、处理键盘遮挡控件

一、定位widget(应用场景:登录按钮被弹出的键盘遮挡,想要弹出键盘的时候整体页面上移)

1、初始化一个GlobalKey

GlobalKey _globalKey = GlobalKey();
复制代码

2、要监听的控件(登录按钮)

Container(
  key:_globalKey,
  child: Text("登录按钮"),
),
复制代码

3、获取该控件的属性(登录按钮)

//获取监听的widget
final RenderBox box = _globalKey.currentContext.findRenderObject();
//获取widget距顶部的偏移(这一步获取的是container距离顶部(0.0)的距离)
final topLeftPosition = box.localToGlobal(Offset.zero);
//获取该widget距底部的长度(屏幕高度-距离顶部的高度-margin.top-自身高度)
final bottom = SS().screenHeight - (topLeftPosition.dy+ SS().h(80));
复制代码

二、获取键盘高度,并定位控件的位置,通过scrollview滑动来避免键盘遮挡控件

class _RegisterTelPageState extends State<RegisterTelPage> with WidgetsBindingObserver {

   ScrollController _scrollController = ScrollController();
   GlobalKey _globalKey = GlobalKey();
   
     @override
      void didChangeMetrics() {
        // TODO: implement didChangeMetrics
        super.didChangeMetrics();
        WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          //弹出的键盘高度
          double height = MediaQuery.of(context).viewInsets.bottom;
          //获取监听的widget
          final RenderBox box = _globalKey.currentContext.findRenderObject();
          //获取widget距顶部的偏移
          final topLeftPosition = box.localToGlobal(Offset.zero);
          //获取该widget距底部的长度
          final bottom = SS().screenHeight - (topLeftPosition.dy+ SS().h(80));
          //判断当收起键盘,页面滑动到初始位置
          if(height == 0){
            _scrollController.jumpTo(0);
          } else {
            //判断键盘挡住控件就滑动
            if (height - bottom > 0) {
            //这里让scrollView向上滑动,滑动到控件距离键盘
              _scrollController.animateTo(height - bottom, duration: Duration(milliseconds: 100), curve: Curves.easeInSine);
            }
          }
        });
      }

      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
   
   
}
复制代码

这里页面用SingleChildScrollview包一层(如果下面Container里面的内容没有超过屏幕高度,可能不会滑动)

SingleChildScrollView(
   controller: _scrollController,
   scrollDirection: Axis.vertical,
   physics: ClampingScrollPhysics(),
   child:Container(),
}
   
   
   
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享