02_Flutter自定义Sliver组件实现分组列表吸顶效果

2023-10-23 08:50

本文主要是介绍02_Flutter自定义Sliver组件实现分组列表吸顶效果,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

02_Flutter自定义Sliver组件实现分组列表吸顶效果

一.先上效果图

在这里插入图片描述

二.列表布局实现

比较简单,直接上代码,主要使用CustomScrollView和SliverToBoxAdapter实现

_buildSection(String title) {return SliverToBoxAdapter(child: RepaintBoundary(child: Container(height: 50,color: Colors.brown,alignment: Alignment.center,child: Text(title),),));
}_buildItem(String title) {return SliverToBoxAdapter(child: RepaintBoundary(child: Container(padding: const EdgeInsets.symmetric(horizontal: 15),height: 70,color: Colors.cyanAccent,alignment: Alignment.centerLeft,child: Text(title),),));
}CustomScrollView(slivers: [_buildSection("蜀汉五虎将"),_buildItem("关羽"),_buildItem("张飞"),_buildItem("赵云"),_buildItem("马超"),_buildItem("黄忠"),_buildSection("虎贲双雄"),_buildItem("许褚"),_buildItem("典韦"),_buildSection("五子良将"),_buildItem("张辽"),_buildItem("乐进"),_buildItem("于禁"),_buildItem("张郃"),_buildItem("徐晃"),_buildSection("八虎骑"),_buildItem("夏侯惇"),_buildItem("夏侯渊"),_buildItem("曹仁"),_buildItem("曹纯"),_buildItem("曹洪"),_buildItem("曹休"),_buildItem("夏侯尚"),_buildItem("曹真")],
)

在这里插入图片描述

三.SliverToBoxAdapter和SliverPersistentHeader

可以使用Flutter提供的SliverPersistentHeader组件实现,在使用SliverPersistentHeader时要求我们明确指定子控件的高度,不支持吸顶上推效果,使用起来不够灵活,所以我们参考并结合SliverToBoxAdapter和SliverPersistentHeader源码,自己实现一个自适应高度的吸顶Sliver组件,并在此基础上一步步实现吸顶上推效果。

  • 编写StickySliverToBoxAdapter类,继承自SingleChildRenderObjectWidget
class StickySliverToBoxAdapter extends SingleChildRenderObjectWidget {const StickySliverToBoxAdapter({super.key,super.child});RenderObject createRenderObject(BuildContext context) => _StickyRenderSliverToBoxAdapter();}

SingleChildRenderObjectWidget类要求我们自己实现createRenderObject方法,返回一个RenderObject对象,而对于一个S liver组件而言,这个RenderObject必须是RenderSilver的子类。

  • 编写_StickyRenderSliverToBoxAdapter,继承RenderSliverSingleBoxAdapter
class _StickyRenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter {void performLayout() {// TODO: implement performLayout}}

RenderSliverSingleBoxAdapter要求子类实现performLayout方法,performLayout会对widegt的布局和绘制做控制,实现吸顶效果的关键就在于performLayout方法的实现。先依次看下SliverToBoxAdapter和SliverPersistentHeader对应RenderObject的performLayout相关方法的实现。

  • RenderSliverToBoxAdapter#performLayout

void performLayout() {if (child == null) {geometry = SliverGeometry.zero;return;}final SliverConstraints constraints = this.constraints;//摆放子View,并把constraints传递给子Viewchild!.layout(constraints.asBoxConstraints(), parentUsesSize: true);//获取子View在滑动主轴方向的尺寸final double childExtent;switch (constraints.axis) {case Axis.horizontal:childExtent = child!.size.width;case Axis.vertical:childExtent = child!.size.height;}final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: childExtent);final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: childExtent);assert(paintedChildSize.isFinite);assert(paintedChildSize >= 0.0);//更新SliverGeometrygeometry = SliverGeometry(scrollExtent: childExtent,paintExtent: paintedChildSize,cacheExtent: cacheExtent,maxPaintExtent: childExtent,hitTestExtent: paintedChildSize,hasVisualOverflow: childExtent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,);//更新paintOffset,由滑动偏移量constraints.scrollOffset决定setChildParentData(child!, constraints, geometry!);
}
  • RenderSliverFloatingPersistentHeader#performLayout

SliverPersistentHeader的performLayout方法中调用了updateGeometry方法去更新geometry,而吸顶的关键就在updateGeometry方法中,也就是paintOrigin的值。constraints.overlap的值代表前一个Sliver和当前Sliver被覆盖部分的高度。


double updateGeometry() {final double minExtent = this.minExtent;final double minAllowedExtent = constraints.remainingPaintExtent > minExtent ?minExtent :constraints.remainingPaintExtent;final double maxExtent = this.maxExtent;final double paintExtent = maxExtent - _effectiveScrollOffset!;final double clampedPaintExtent = clampDouble(paintExtent,minAllowedExtent,constraints.remainingPaintExtent,);final double layoutExtent = maxExtent - constraints.scrollOffset;final double stretchOffset = stretchConfiguration != null ?constraints.overlap.abs() :0.0;geometry = SliverGeometry(scrollExtent: maxExtent,paintOrigin: math.min(constraints.overlap, 0.0),paintExtent: clampedPaintExtent,layoutExtent: clampDouble(layoutExtent, 0.0, clampedPaintExtent),maxPaintExtent: maxExtent + stretchOffset,maxScrollObstructionExtent: minExtent,hasVisualOverflow: true, // Conservatively say we do have overflow to avoid complexity.);return 0.0;
}

四.吸顶效果实现

直接把上面updateGeometry中设置SliverGeometry的代码拷贝到_StickyRenderSliverToBoxAdapter#performLayout实现中,maxExtent和minExtent这两个值是由SliverPersistentHeader传入的SliverPersistentHeaderDelegate对象提供的。这里可以自己去看SliverPersistentHeaderDelegate的源码,就不多废话了。我们只需要把maxExtent和minExtent这两个值都改为子控件在主轴方向的尺寸大小即可。

 _buildSection(String title) {return StickySliverToBoxAdapter(child: RepaintBoundary(child: Container(height: 50,color: Colors.brown,alignment: Alignment.center,child: Text(title),),));}class _StickyRenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter {void performLayout() {if (child == null) {geometry = SliverGeometry.zero;return;}final SliverConstraints constraints = this.constraints;//摆放子View,并把constraints传递给子Viewchild!.layout(constraints.asBoxConstraints(), parentUsesSize: true);//获取子View在滑动主轴方向的尺寸final double childExtent;switch (constraints.axis) {case Axis.horizontal:childExtent = child!.size.width;case Axis.vertical:childExtent = child!.size.height;}final double minExtent = childExtent;final double minAllowedExtent = constraints.remainingPaintExtent > minExtent ?minExtent : constraints.remainingPaintExtent;final double maxExtent = childExtent;final double paintExtent = maxExtent;final double clampedPaintExtent = clampDouble(paintExtent,minAllowedExtent,constraints.remainingPaintExtent,);final double layoutExtent = maxExtent - constraints.scrollOffset;geometry = SliverGeometry(scrollExtent: maxExtent,paintOrigin: min(constraints.overlap, 0.0),paintExtent: clampedPaintExtent,layoutExtent: clampDouble(layoutExtent, 0.0, clampedPaintExtent),maxPaintExtent: maxExtent,maxScrollObstructionExtent: minExtent,hasVisualOverflow: true, // Conservatively say we do have overflow to avoid complexity.);}
}

在这里插入图片描述

仔细看上面的效果,貌似只有第一个Sliver吸顶了,我们把分组item的背景改成透明的,再来看看效果,就知道怎么回事了😄。

在这里插入图片描述

可以看到,所有的分组section都已经吸顶了,只不过吸顶位置都是0,并且前一个section把后一个section覆盖了,我们下一步实现上推功能后,这个问题自热而然的就解决了。

五.实现上推效果

在这里插入图片描述

如图,当前section与前一个section重合了多少,前一个section就往上移动多少,也就是移动constraints.overlap即可,往下滑动也是同样的道理。

//查找前一个吸顶的section
RenderSliver? _prev() {if(parent is RenderViewportBase) {RenderSliver? current = this;while(current != null) {current = (parent as RenderViewportBase).childBefore(current);if(current is _StickyRenderSliverToBoxAdapter && current.geometry != null) {return current;}}}return null;
}
void performLayout() {if (child == null) {geometry = SliverGeometry.zero;return;}final SliverConstraints constraints = this.constraints;//摆放子View,并把constraints传递给子Viewchild!.layout(constraints.asBoxConstraints(), parentUsesSize: true);//获取子View在滑动主轴方向的尺寸final double childExtent;switch (constraints.axis) {case Axis.horizontal:childExtent = child!.size.width;case Axis.vertical:childExtent = child!.size.height;}final double minExtent = childExtent;final double minAllowedExtent = constraints.remainingPaintExtent > minExtent ?minExtent : constraints.remainingPaintExtent;final double maxExtent = childExtent;final double paintExtent = maxExtent;final double clampedPaintExtent = clampDouble(paintExtent,minAllowedExtent,constraints.remainingPaintExtent,);final double layoutExtent = maxExtent - constraints.scrollOffset;geometry = SliverGeometry(scrollExtent: maxExtent,paintOrigin: min(constraints.overlap, 0.0),paintExtent: clampedPaintExtent,layoutExtent: clampDouble(layoutExtent, 0.0, clampedPaintExtent),maxPaintExtent: maxExtent,maxScrollObstructionExtent: minExtent,hasVisualOverflow: true, // Conservatively say we do have overflow to avoid complexity.);//上推关键代码: 当前吸顶的Sliver被覆盖了多少,前一个吸顶的Sliver就移动多少RenderSliver? prev = _prev();if(prev != null && constraints.overlap > 0) {setChildParentData(_prev()!, constraints.copyWith(scrollOffset: constraints.overlap), _prev()!.geometry!);}
}

搞定,可以洗洗睡了,嘿嘿。

在这里插入图片描述

六.Fixed: 吸顶section点击事件失效

重写childMainAxisPosition方法返回0即可

class _StickyRenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter {...// 必须重写,否则点击事件失效。double childMainAxisPosition(covariant RenderBox child) => 0.0;}

这篇关于02_Flutter自定义Sliver组件实现分组列表吸顶效果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/266793

相关文章

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P