Flutter如何实现下拉刷新和上拉加载更多,内含福利
在Flutter中,你可以使用RefreshIndicator
和ListView
来实现下拉刷新,使用ScrollController
来实现上拉加载更多。以下是一个简单的示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<String> items = List.generate(20, (i) => "Item ${i + 1}");
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
_scrollController.addListener(() {
if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
setState(() {
items.addAll(List.generate(20, (i) => "Item ${i + 21}"));
});
}
});
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
Future<void> _refresh() async {
await Future.delayed(Duration(seconds: 2));
setState(() {
items = List.generate(20, (i) => "Item ${i + 1}").toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('下拉刷新和上拉加载'),
),
body: RefreshIndicator(
onRefresh: _refresh,
child: ListView.builder(
controller: _scrollController,
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
),
);
}
}
在这个示例中,RefreshIndicator
包裹了ListView
,它会在用户下拉时触发_refresh
方法来刷新数据。ScrollController
监听滚动事件,当列表滚动到底部时,会加载更多数据。这里使用了Future.delayed
来模拟异步数据加载,实际应用中应替换为实际的数据加载逻辑。
评论已关闭