要求在切换tab的时候,视图滚动到指定 widget,
我们第一时间会想到 使用ScrollView,ScrollController 能用来控制位置的滚动,而且网上相关文章也比较少,大多是用 controller 的 jumpTo 和 animateTo 来控制位置。
效果如图
但是这样需要去给指定的组件,设置key,通过 key 来获取位置
比如
RenderBox box = mKey.currentContext.findRenderObject();
Offset offset = box.localToGlobal(Offset.zero);
_controller.jumpTo(offset.dy);
但是这样会受到 appbar等一些因素影响导致结果不准确,而且在页面中有多个需要切换滚动位置的时候会有很大的误差。
如果要实现上图这种点击切换位置有个官方提供的方法
Scrollable.ensureVisible(mKey.currentContext);
一行代码搞定
如果要判断滚动的位置关联 tab 的状态
double offset = _controller.offset + 44.h;
LogUtils.v("${_controller.position.pixels + 44}====${offset.toInt()}");
if (offset < getY(topKey.currentContext)) {
tabController.animateTo(0,duration: Duration.zero);
} else if (offset > getY(topKey.currentContext) && offset < getY(hotKey.currentContext)) {
tabController.animateTo(1,duration: Duration.zero);
} else if (offset > getY(hotKey.currentContext) && offset < getY(detailsKey.currentContext)) {
tabController.animateTo(2,duration: Duration.zero);
} else if (offset > getY(detailsKey.currentContext)) {
tabController.animateTo(3,duration: Duration.zero);
// tabController.index();
}
double getY(BuildContext buildContext) {
RenderBox box = buildContext.findRenderObject();
Offset offset = box.localToGlobal(Offset.zero);
double animatHeight = 0.0;
scrollHeight = BaseTheme.getTopStatusBarHeight();
double d = Scrollable.of(buildContext).position.pixels;
animatHeight = _controller.offset +
offset.dy -
MediaQueryData.fromWindow(ui.window).padding.top -
scrollHeight;
return animatHeight;
}
建议自定义tab,否则滚动动画 和 tabController.animateTo 会产生冲突