Flutter开发之——下拉刷新
在Flutter中实现下拉刷新,可以使用RefreshIndicator
控件。以下是一个简单的示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: RefreshIndicatorPage(),
);
}
}
class RefreshIndicatorPage extends StatefulWidget {
@override
_RefreshIndicatorPageState createState() => _RefreshIndicatorPageState();
}
class _RefreshIndicatorPageState extends State<RefreshIndicatorPage> {
List<String> items = List.generate(20, (i) => "Item ${i + 1}");
Future<void> _refreshList() async {
await Future.delayed(Duration(seconds: 2)); // 模拟网络请求
setState(() {
items = List.generate(20, (i) => "Refreshed Item ${i + 1}");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('下拉刷新示例'),
),
body: RefreshIndicator(
onRefresh: _refreshList,
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
),
);
}
}
在这个示例中,RefreshIndicator
控件被用来包裹ListView
,并且当用户下拉列表到顶部时触发刷新操作。onRefresh
回调函数 _refreshList
被调用,并模拟了一个异步的延时操作来模拟网络请求(实际应用中应该是网络请求),然后更新列表的内容。
评论已关闭