在flutter中想要实现下拉刷新效果如果只是实现android 原生的效果的话,
只需要在Scrollable 外层嵌套RefreshIndicator 即可
例子
getListBody() {
if (list_str.length < 100) {
loadDate();
}
return RefreshIndicator(
onRefresh: () async {
setState(() {
list_str.clear();
loadDate();
});
},
child: ListView.separated(
itemCount: list_str.length,
separatorBuilder: (context, index) => Divider(),
itemBuilder: (context, index) {
if (list_str[index] == endTag) {
return Container(
padding: const EdgeInsets.all(16.0),
alignment: Alignment.center,
child: SizedBox(
width: 24.0,
height: 24.0,
child: CircularProgressIndicator(strokeWidth: 2.0)),
);
} else {
return Container(
width: double.infinity,
alignment: Alignment.center,
padding: const EdgeInsets.all(10),
child: inflateText(list_str[index], Colors.blueAccent, 16),
);
}
}),
);
}
貌似这里没什么好说的,下面主要来说一下自定义下拉刷新方式
CupertinoSliverRefreshControl
使用CupertinoSliverRefreshControl 就必须要了解CustomScrollView, CustomScrollView可以连接多个Scrollable ,让他们具有滑动一致性,并可以实现复杂的折叠效果,
先来看一下CupertinoSliverRefreshControl构造方法
const CupertinoSliverRefreshControl({
Key key,
this.refreshTriggerPullDistance = _defaultRefreshTriggerPullDistance,///触发刷新的距离
this.refreshIndicatorExtent = _defaultRefreshIndicatorExtent,///刷新指示器范围
/// 根据 刷新状态和距离返回一个Widget ,这个就是自定义的布局
this.builder = buildRefreshIndicator,
/// 触发刷新后的回调
this.onRefresh,
})
/// 上面那个builder 方法
typedef RefreshControlIndicatorBuilder = Widget Function(
BuildContext context,
RefreshIndicatorMode refreshState,///刷新状态
double pulledExtent,///已下拉的距离
double refreshTriggerPullDistance,///下拉多杀触发刷新
double refreshIndicatorExtent,///下拉刷新过程中等待刷新的距离
);
例子
Material(
child: CustomScrollView(
///越界回弹效果
physics: BouncingScrollPhysics(),
slivers: [
CupertinoSliverRefreshControl(
refreshIndicatorExtent: 60,/// 刷新过程中悬浮高度
refreshTriggerPullDistance: 100,///触发刷新的距离
/// 自定义布局
builder: (context,buildRefreshindictor,pulledExtent,refreshTriggerPullDistance,refreshIndicatorExtent){
printString('pulledExtent : ${pulledExtent} ,refreshTriggerPullDistance : ${refreshTriggerPullDistance} refreshIndicatorExtent:${refreshIndicatorExtent}');
return Container(
color: Colors.redAccent,
height: 150,
alignment: Alignment.center,
child: AnimatedOpacity(
duration: Duration(milliseconds: 300),
//opacity: top == 80.0 ? 1.0 : 0.0,
opacity: 1.0,
child: Text(RefreshIndicatorMode.done==buildRefreshindictor? '已拉动:${pulledExtent.round()} 松开刷新': '已拉动:${pulledExtent.round()} 下拉刷新',
style: TextStyle(fontSize: 12.0),
)),
);
},
///触发刷新回调
onRefresh: () async {
await Future.delayed(Duration(seconds: 3));
printString('CupertinoSliverRefreshControl onRefresh');
},
),
],
),
);
GIF 2020-8-27 15-29-26.gif
但是我发现如果不使用默认的下拉效果,子控件高度如果无法达到一个屏幕的高度,这个下拉刷新就不会触发,这个需要解决一下,我会在接下来的学习过程中进一步优化的,
我学习flutter的整个过程都记录在里面了
https://www.jianshu.com/c/36554cb4c804
最后附上demo 地址
网友评论