一、下拉刷新
在Flutter中有一个RefreshIndicator,它是一个下拉刷新的widget,通过它我们可实现列表的下拉刷新的操作。
二、上拉加载
在Flutter中有一个ScrollController 列表支持设置controller参数,通过ScrollController监听列表滚动的位置,来实现加载更多的功能。
demo:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
List list = ['北京','上海','广州','深圳','杭州','苏州','成都','重庆','宁夏','银川'];
int index = 0;
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() {
return _MyAppState();
}
}class _MyAppState extends State {
ScrollController _scrollController = ScrollController();
@override
void initState() {
_scrollController.addListener((){
if(_scrollController.position.pixels==_scrollController.position.maxScrollExtent){
_loadData();
}
});
super.initState();
}@override
void dispose() {
_scrollController.dispose();
super.dispose();
}@override
Widget build(BuildContext context) {
return new MaterialApp(
title: '下拉刷新',
home: Scaffold(
appBar: AppBar(
title: Text("下拉刷新"),
),
body: RefreshIndicator(
child: ListView(
controller: _scrollController,
children: _buildList(),
),
onRefresh: _refresh,
),
),
);
}List _buildList(){
return list.map((city)=>_item(city)).toList();
}
_loadData() async{
await Future.delayed(Duration(microseconds: 200));
setState(() {
List newList = List.from(list);
newList.addAll(list);
list = newList;
});
}Future _refresh() async{
await Future.delayed(Duration(seconds: 2));
setState(() {
list.insert(0, "我是第${++index}下拉刷新加进来的");
});
return null;
}
Widget _item(String city){
return Container(
height: 80,
margin: EdgeInsets.only(bottom: 5),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.blue),
child: Text(
city,
style: TextStyle(color: Colors.white,fontSize: 20),
),
);
}
}
【Dart|Flutter之下拉刷新和上拉加载】
推荐阅读
- 回顾 Flutter 2021 重要时刻,奉上虎年红包封面喜迎新年!
- Flutter实现左侧边栏导航
- 如何在 Flutter 创建一个后台任务
- Flutter Convex Bottom 底部导航
- Flutter动态化框架Thresh
- 基于 Riverpod 的 Flutter 状态管理
- Flutter 2022 产品路线图发布
- Flutter 插件库
- Windows Running “flutter pub get“ in XXX卡死
- Flutter之下拉刷新,上拉加载更多