1. 前言
SliverFloatingHeader 是 3.27.0 中新增组件之一,它可以让开发者更容易地实现头部浮动的功能。先通过本文两个案例,看一下它的效果,SliverFloatingHeader 的特点是:
向上滑动时内容组件会移出屏幕,向下滑动时,会展示出来。
FlutterUnit 之前也有类似的效果,是通过自定义 SliverPersistentHeader 代理器实现的,比较麻烦。SliverFloatingHeader 支持之后,可以轻松完成同样的功能:
官方案例 | FlutterUnit 首页 |
---|---|
1. 官方案例分析
SliverFloatingHeader 组件在使用上非常简单,它和其他的 Sliver 组件一样,只有用于滑动视口中。比如这里通过 CustomScrollView
盛纳多个 Sliver 滑片:
- SliverFloatingHeader 中的 child 组件设置头部组件内容。这里通过 ListHeader 组件关键内容,它是一个非 Sliver 的组件。
CustomScrollView(
slivers: <Widget>[
SliverFloatingHeader(
child: ListHeader(
text:
'SliverFloatingHeader\nScroll down a little to show\nScroll up a little to hide',
),
snapMode: FloatingHeaderSnapMode.overlay,
),
ItemList(),
],
),
- ItemList 是 SliverList 组件构建的 50 个滑动条目,在 SliverFloatingHeader 之下
class ItemList extends StatelessWidget {
const ItemList({super.key, this.itemCount = 50});
final int itemCount;
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return SliverList(
delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
return Card(
color: colorScheme.onSecondary,
child: ListTile(textColor: colorScheme.secondary, title: Text('Item $index')),
);
}, childCount: itemCount),
);
}
}
这样就实现了 ListHeader 头部内容的上述滚动效果。
2. FlutterUnit 首页使用 SliverFloatingHeader
FlutterUnit 首页头部的搜索标题栏,会随着下滑消失、上滑出现。有了 SliverFloatingHeader 之后,只需要如下非常简单地处理即可:其中头部栏的构建交由 StandardHomeSearch
组件负责,可以无缝衔接:
总得来说,SliverFloatingHeader 的功能非常简单,只要有想让头部栏下滑消失、上滑出现的场景,用 SliverFloatingHeader 套一下就可以了。
3. SliverFloatingHeader 的其他参数
进入 SliverFloatingHeader 源码中的构造函数中瞥一眼可以看出,它还有两个可配置的参数:
其中 snapMode
类型是 FloatingHeaderSnapMode 枚举,默认是 overlay
模式,两者区别在于:
- overlay: 向下滑动,头部展开的过程中,下方列表内容不发生相对偏移。
- scroll:向下滑动,头部展开的过程中,下方列表内容也会同时滑动。
overlay | scroll |
---|---|
enum FloatingHeaderSnapMode {
overlay,
scroll,
}
animationStyle
的类型是 AnimationStyle
, 用于动画样式的配置,包括正反动画时长、曲线:
class AnimationStyle with Diagnosticable {
/// Creates an instance of Animation Style class.
AnimationStyle({
this.curve,
this.duration,
this.reverseCurve,
this.reverseDuration,
});
4. SliverFloatingHeader 源码实现简看
下面来简单看一下 SliverFloatingHeader 的源码实现,从中汲取一些有用的知识。从上面的构造中可以看出 SliverFloatingHeader
是一个 StatefulWidget
, 它会依赖 _SliverFloatingHeaderState
状态类完成构建组件的任务。
有状态组件的必要性是,该组件需要进行动画效果,状态类混入了 SingleTickerProviderStateMixin
。并将自身作为 Ticker 创建器传给 _SliverFloatingHeader
组件:
_SliverFloatingHeader
是一个单子渲染组件,维护 _RenderSliverFloatingHeader
渲染对象。SliverFloatingHeader 的两个属性,也是用于该渲染对象中的:
同步标题的内容通过 _SnapTrigger
构建,这里值得学习一下普通组件如何获取滚动的位置,进行联动。如下所示: 在 didChangeDependencies
中,通过 Scrollable.maybeOf(context)
可以获取 ScrollableState 滑动状态类, 对其中的 position#isScrollingNotifier
进行监听,可以得到是否正在滑动的监听,
正在滑动中时,触发 isScrollingListener
回调,其中通过上下文寻找 _RenderSliverFloatingHeader
渲染对象,触发它的 isScrollingUpdate
更新位置。
尾声
关于 _RenderSliverFloatingHeader
实现的具体细节,感兴趣的朋友可以自己研究一下。总得来说 SliverFloatingHeader 组件对于使用者来说,简单有强大,可以方便地解决场景中的痛点。希望本文可以帮到你,更多的组件介绍分享,敬请期待 ~
更多文章和视频知识资讯,大家可以关注我的公众号、掘金和 B 站 。