flutter实现上拉加载下拉刷新
在Flutter中,你可以使用RefreshIndicator
和ListView
来实现下拉刷新,使用ScrollController
来实现上拉加载。以下是一个简单的示例代码:
import 'package:flutter/material.dart';
class RefreshLoadList extends StatefulWidget {
@override
_RefreshLoadListState createState() => _RefreshLoadListState();
}
class _RefreshLoadListState extends State<RefreshLoadList> {
final ScrollController _scrollController = ScrollController();
List<String> _items = List.generate(30, (index) => "Item ${index + 1}");
bool _isLoading = false;
@override
void initState() {
super.initState();
_scrollController.addListener(_scrollListener);
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _scrollListener() {
if (_isLoading) return;
if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
setState(() {
_isLoading = true;
});
// 模拟加载更多数据
Future.delayed(Duration(seconds: 2), () {
setState(() {
_items.addAll(List.generate(10, (index) => "Item ${_items.length + 1}"));
_isLoading = false;
});
});
}
}
Future<void> _refreshList() async {
await Future.delayed(Duration(seconds: 2));
setState(() {
_items = List.generate(30, (index) => "Item ${index + 1}");
});
}
@override
Widget build(BuildContext context) {
return RefreshIndicator(
onRefresh: _refreshList,
child: ListView.builder(
controller: _scrollController,
itemCount: _items.length,
itemBuilder: (context, index) {
return _isLoading && index == _items.length - 1
? Center(child: CircularProgressIndicator())
: ListTile(title: Text(_items[index]));
},
),
);
}
}
void main() {
runApp(MaterialApp(home: RefreshLoadList()));
}
在这个示例中,RefreshLoadList
是一个有状态的小部件,它包含一个ListView
和一个ScrollController
。_scrollListener
方法监听滚动事件,当用户到达列表底部时,它会检查是否正在加载,如果没有,它会模拟加载更多数据。_refreshList
方法处理下拉刷新操作,它会更新列表中的项目。这个例子使用了Future.delayed
来模拟异步数据加载,实际应用中应该替换为实际的数据加载逻辑。
评论已关闭