在Flutter中有一个RefreshIndicator
,它是一个下拉刷新的widget,通过它我们可以实现列表的下拉刷新。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
List<String> cityNames = [ '北京', '上海', '广州', '深圳', '杭州', '苏州', '成都', '武汉', '郑州', '洛阳', '厦门', '青岛', '拉萨' ];
class MyApp extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Widget build(BuildContext context) {
final title = '高级功能列表下拉刷新与上拉加载更多功能实现';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView(
children: _buildList(),
),
),
),
);
}
Future<Null> _handleRefresh() async {
await Future.delayed(Duration(seconds: 2));
setState(() {
cityNames = cityNames.reversed.toList();
});
return null;
}
List<Widget> _buildList() {
return cityNames.map((city) => _item(city)).toList();
}
Widget _item(String city) {
return Container(
height: 80,
margin: EdgeInsets.only(bottom: 5),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.teal),
child: Text(
city,
style: TextStyle(color: Colors.white, fontSize: 20),
),
);
}
}
为了给列表添加上了加载更多的功能,我们可以借助ScrollController
,列表支持设置controller
参数,通过ScrollController
监听列表滚动的位置,来实现加载更多的功能。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
List<String> cityNames = [ '北京', '上海', '广州', '深圳', '杭州', '苏州', '成都', '武汉', '郑州', '洛阳', '厦门', '青岛', '拉萨' ];
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
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) {
final title = '高级功能列表下拉刷新与上拉加载更多功能实现';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView(
controller: _scrollController,
children: _buildList(),
),
),
),
);
}
_loadData() async {
await Future.delayed(Duration(milliseconds: 200));
setState(() {
List<String> list = List<String>.from(cityNames);
list.addAll(cityNames);
cityNames = list;
});
}
Future<Null> _handleRefresh() async {
await Future.delayed(Duration(seconds: 2));
setState(() {
cityNames = cityNames.reversed.toList();
});
return null;
}
List<Widget> _buildList() {
return cityNames.map((city) => _item(city)).toList();
}
Widget _item(String city) {
return Container(
height: 80,
margin: EdgeInsets.only(bottom: 5),
alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.teal),
child: Text(
city,
style: TextStyle(color: Colors.white, fontSize: 20),
),
);
}
}
解锁Flutter开发新姿势,,系统掌握Flutter开发核心技术。
了解课程