Flutter教程:多个infinity_slider嵌套实现滑动互联的效果
目标
- 多个
infinity_slider
嵌套实现滑动互联的效果
完整代码
- pub: pub.dev/packages/in…
- github: github.com/herghost000…
思路
- 通过widget树找到父
infinity_slider
控件 - 使用
NotificationListener
监听当前infinity_slider
控件滚动 - 使用父
infinity_slider
控件的_pageController
移动父infinity_slider
控件的位置 - 禁用当前
infinity_slider
控件在父infinity_slider
控件未抵达边缘时产生的光晕效果
步骤
1) 找到父infinity_slider
控件
在InfinitySlider
类中添加此代码
static InfinitySliderState of(BuildContext context) {
return context.ancestorStateOfType(TypeMatcher<InfinitySliderState>());
}
复制代码
在initState
中初始化下方代码
InfinitySliderState _ancestor;
@override
void initState() {
_linkAncestorIfNeeded();
}
void _linkAncestorIfNeeded() {
_ancestor = InfinitySlider.of(context);
}
复制代码
2) 监听当前infinity_slider
控件滚动
@override
Widget build(BuildContext context) {
return NotificationListener(
onNotification: _handleScrollNotification,
child: PageView.builder(
......
)
);
}
void _handleScrollNotification(ScrollNotification notification) {
}
复制代码
3) 控制父infinity_slider
控件滚动
bool _handleScrollNotification(ScrollNotification notification) {
if (notification is OverscrollNotification && _ancestor != null) {
if (_canLinkWithAncestorScroll(notification.overscroll < 0)) {
_ancestor._pageController.position
.moveTo(_ancestor._pageController.offset + notification.overscroll);
}
}
}
bool _canLinkWithAncestorScroll(bool onLeftEdge) {
if (_ancestor == null) return false;
return (onLeftEdge &&
_ancestor._pageController.offset !=
_ancestor._pageController.position.minScrollExtent) ||
((!onLeftEdge &&
_ancestor._pageController.offset !=
_ancestor._pageController.position.maxScrollExtent));
}
复制代码
4) 禁用infinity_slider
控件在与父infinity_slider
控件联动产生的光晕
@override
Widget build(BuildContext context) {
return NotificationListener(
onNotification: _handleScrollNotification,
child: NotificationListener(
onNotification: _handleGlowNotification,
child: PageView.builder(
......
)
)
);
)
bool _handleGlowNotification(OverscrollIndicatorNotification notification) {
if (notification.depth == 0 &&
_canLinkWithAncestorScroll(notification.leading)) {
notification.disallowGlow();
return true;
}
return false;
}
作者:么姐
链接:https://juejin.im/post/5d6c973ae51d45620064bb92
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
THE END