下拉刷新与上拉加载更多在一般项目中很多地方都会用到,来看看Flutter中最简单的实践:
1 下拉刷新(用变化数据来演示)
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class PullToRefreshPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _PullToRefreshPage();
}
}
class _PullToRefreshPage extends State<PullToRefreshPage> {
List<int> items = List.generate(16, (index) => index);
ScrollController _scrollController = new ScrollController();
bool isLoading = false;
Future<Null> _handleRefresh() async {
await Future.delayed(Duration(seconds:3),() {
print('refresh');
setState(() {
items.clear();
items = List.generate(30, (index) => index);
return null;
});
});
}
@override
Widget build(BuildContext context) {
return
Scaffold(
appBar: AppBar(title: Text("Refresh"),),
body: new RefreshIndicator(
child: ListView.builder(
itemCount: items.length,
itemBuilder: (context,index) {
return ListTile(title: Text("Index$index"),);
},
),
onRefresh:_handleRefresh
),
);
}
2 上拉加载更多
class _PullToRefreshPage extends State<PullToRefreshPage> {
List<int> items = List.generate(16, (index) => index);
ScrollController _scrollController = new ScrollController();
bool isLoading = false;
@override
Widget build(BuildContext context) {
return
Scaffold(
appBar: AppBar(
title: Text("LoadMore"),
),
body: ListView.builder(
itemCount: items.length + 1,
itemBuilder: (context, index) {
// return ListTile(
// title: Text("Index$index"));
print('------>--index---$index');
if(index == items.length) {
// return _buildLoadText();
return _buildProgressIndicator();
} else {
return ListTile(title:Text("Index$index"));
}
},
controller: _scrollController,
)
);
}
Widget _buildLoadText() {
return Container(child: Padding(
padding: const EdgeInsets.all(18.0),
child:Center(
child: Text("加载中....."),
)
));
}
Widget _buildProgressIndicator() {
return new Padding(
padding:const EdgeInsets.all(8.0),
child:new Center(
child:new CircularProgressIndicator(),
)
);
}
@override
void initState() {
// TODO: implement initState
super.initState();
print('---_scrollController---->');
_scrollController.addListener(() {
print('---initState---->');
if(_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
print('loadMore');
_getMoreData();
}
print('---_scrollController----End-->');
});
}
Future _getMoreData() async {
List<int> newEntries = await makeHttpRequest(items.length,items.length+10);
setState(() {
items.addAll(newEntries);
isLoading = false;
});
}
Future<List<int>> makeHttpRequest(int from,int to) async {
return Future.delayed(Duration(seconds:2),() {
return List.generate(to-from,(i) => i+from);
});
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
_scrollController.dispose();
}
}