Flutter 滚动到指定Widget位置

作者: 6u7 | 来源:发表于2019-07-22 13:58 被阅读1次

    1.新增globalKey

    final GlobalKey globalKey=GlobalKey();

    2,需要监控的widget的key设置成新增的globalkey

    ListView(

    controller:_controller

    children: [

            Container(height:200,width: double.infinity,color: Colors.red,),

            Container(height:200,width: double.infinity,color: Colors.yellow,),

            Container(height:200,width: double.infinity,color: Colors.blue,),

            Container(

                key:globalKey,

                height:200,width: double.infinity,color: Colors.pink,

            ),

            Container(height:200,width: double.infinity,color: Colors.cyan,),

        ],

    )

    3,获取widget相对于当前页面显示状态下的位置 

    //获取position

    RenderBox box =globalKey.currentContext.findRenderObject();

    Offset offset = box.localToGlobal(Offset.zero);

    //获取size

    Size size = box.size;

    Size size =globalKey.currentContext.size;

    4,获取的Widget高度包含状态栏和appbar高度以及ListVIew的offset,计算所要滚动到的位置并使用_controller滚动到指定位置

    _scrollToWidget(){

    RenderBox box =globalKey.currentContext.findRenderObject();

        Offset offset = box.localToGlobal(Offset.zero);

        double animatHeight =0.0;

        if(offset.dy ==MediaQueryData.fromWindow(window).padding.top +56.0)return;

        animatHeight =_controller.offset + offset.dy -MediaQueryData.fromWindow(window).padding.top -56.0;

    _controller.animateTo(animatHeight, duration:Duration(milliseconds:500), curve: Curves.decelerate);

    }

    相关文章

      网友评论

        本文标题:Flutter 滚动到指定Widget位置

        本文链接:https://www.haomeiwen.com/subject/tbykfqtx.html