使用 Flutter 提供的 RefreshIndicator 组件 , 可以实现下拉刷新的功能 ;
使用 RefreshIndicator 组件包裹 ListView 组件 ;
在 RefreshIndicator 构造函数中 , 设置 onRefresh 参数 , 为其设置其下拉刷新回调事件 , 当用户下拉刷新时 , 会回调该方法 ;
onRefresh 参数原型如下 , 是一个 RefreshCallback 类型的对象 ;
final RefreshCallback onRefresh;
RefreshCallback 类型是一个返回值为 Future 的方法 ;
typedef RefreshCallback = Future<void> Function();
RefreshIndicator 构造函数原型 :
/// The signature for a function that's called when the user has dragged a
/// [RefreshIndicator] far enough to demonstrate that they want the app to
/// refresh. The returned [Future] must complete when the refresh operation is
/// finished.
///
/// Used by [RefreshIndicator.onRefresh].
typedef RefreshCallback = Future<void> Function();
class RefreshIndicator extends StatefulWidget {
const RefreshIndicator({
Key? key,
required this.child,
this.displacement = 40.0,
this.edgeOffset = 0.0,
required this.onRefresh,
this.color,
this.backgroundColor,
this.notificationPredicate = defaultScrollNotificationPredicate,
this.semanticsLabel,
this.semanticsValue,
this.strokeWidth = 2.0,
this.triggerMode = RefreshIndicatorTriggerMode.onEdge,
})
/// A function that's called when the user has dragged the refresh indicator
/// far enough to demonstrate that they want the app to refresh. The returned
/// [Future] must complete when the refresh operation is finished.
final RefreshCallback onRefresh;
}
import 'package:flutter/material.dart';
var NAMES = [ '宋江', '卢俊义', '吴用', '公孙胜', '关胜',
'林冲', '秦明', '呼延灼', '花荣', '柴进',
'李应', '朱仝', '鲁智深', '武松', '董平',
'张清', '杨志', '徐宁', '索超', '岱宗',
'刘唐', '李逵', '史进', '穆弘' '雷横' ];
/// ListView 垂直列表 , RefreshIndicator 下拉刷新
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
/// 材料设计主题
return MaterialApp(
home: Scaffold(
appBar: AppBar(
/// 标题组件
title: Text("ListView 示例"),
),
/// 列表组件
body: RefreshIndicator(
onRefresh: _onRefresh,
child: ListView(
children: _buildList(),
),
),
),
);
}
/// 下拉刷新回调方法
Future<Null> _onRefresh() async {
/// 强制休眠 1 秒
await Future.delayed(Duration(seconds: 1));
/// 更新状态
setState(() {
/// 将 List 元素翻转
NAMES = NAMES.reversed.toList();
});
return null;
}
/// 创建列表
List<Widget> _buildList(){
/// 遍历 NAMES 数组
/// 调用 map 方法遍历数组元素
return NAMES.map((name) => _generateWidget(name)).toList();
}
Widget _generateWidget(name){
return Container(
height: 80,
margin: EdgeInsets.only(bottom: 5),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.black),
child: Text(
name,
style: TextStyle(
color: Colors.yellowAccent,
fontSize: 20
),
),
);
}
}
执行结果 :
参考资料 :
重要的专题 :
博客源码下载 :