Flutter中文社区Flutter圈子Flutter

Flutter 滚动到指定Widget位置

2019-07-22  本文已影响1人  6u7

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);

}

上一篇下一篇

猜你喜欢

热点阅读