Flutter 项目实战 下拉刷新、上拉加载 九,android面试宝典2024
在Flutter中实现下拉刷新和上拉加载更多,可以使用RefreshIndicator
和ListView
配合使用。以下是一个简单的示例代码:
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, (index) => "Item ${index + 1}");
bool isLoading = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('下拉刷新和上拉加载'),
),
body: RefreshIndicator(
onRefresh: _refresh,
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
if (index < items.length) {
return ListTile(title: Text(items[index]));
} else if (isLoading) {
return Center(child: CircularProgressIndicator());
} else {
return Container();
}
},
physics: AlwaysScrollableScrollPhysics(),
),
),
);
}
Future<void> _refresh() async {
await Future.delayed(Duration(seconds: 2));
setState(() {
items.clear();
items.addAll(List.generate(20, (index) => "New Item ${index + 1}"));
});
}
Future<void> _loadMore() async {
await Future.delayed(Duration(seconds: 2));
setState(() {
isLoading = false;
items.addAll(List.generate(20, (index) => "New Item ${items.length + index + 1}"));
});
}
}
在这个示例中,RefreshIndicator
用于实现下拉刷新功能,通过onRefresh
回调来处理刷新逻辑。ListView.builder
用于构建列表,通过判断索引是否等于列表长度来决定是否显示加载指示器。当用户滚动到列表末尾时,可以在_loadMore
方法中添加加载更多的逻辑。这里使用Future.delayed
来模拟异步加载数据,实际应用中应替换为实际的数据加载逻辑。
评论已关闭