ScrollController animateTo 方法在 NotifcationListener's onNotification 方法期间不会触发



我有一个水平列表视图。在用户松开手指并且 ListView 减速到停止后,我希望视图将最中间的小组件直接放置在 ListView 的中心。

为此,我有一个通知侦听器:

child: NotificationListener<ScrollNotification>(
onNotification: onNotification,
child: ListView.builder(
controller: _controller,
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: 30,
itemBuilder: (BuildContext context, int index) {
return _buildProfileIcon(context, index);
},
),
),

其 onNotifcation 方法检查滚动是否结束:

bool onNotification(ScrollNotification scrollNotification) {
if (scrollNotification is ScrollEndNotification) {
_centerElement(findCenterElement());
}
return null;
}

为了找到已经最接近中心的元素并将其居中:

int findCenterElement() {
double offset = _controller.offset + 2*profileWidth;
int centerishElement = offset < profileWidth
? 0
: ((offset - profileWidth) / profileWidth).ceil();
return centerishElement;
}

void _centerElement(int index) {
RenderBox renderBox = context.findRenderObject();
double viewWidth = renderBox.size.width;
_controller.animateTo(
(profileWidth*index - viewWidth/2 + profileWidth/2),
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}

我有相同的 centerElement(int index( 方法由 GestureDetectors onTap(( 方法在这些配置文件图标小部件(此 ListView 列出的小部件(上调用,并且它很好地将元素居中。设置断点表明,实际上,当 onNotification 作为 ScrollEndNotification 触发时,_centerElement(( 被调用,其中的 _controller.animateTo(( 方法也是如此。但是在 NotificationListener 事件的情况下,animateTo(( 实际上并没有移动列表。

滚动没有尽头,所以不能animateTo某处,

if (scrollNotification is UserScrollNotification && scrollNotification.direction == ScrollDirection.idle) {
scrollcontrol.animateTo(100, duration: Duration(milliseconds: 200), curve: Curves.ease);
}

相关内容

最新更新