ListView 下拉刷新与上拉加载更多
import 'dart:async';import 'package:flutter/material.dart';/*** 有状态StatefulWidget* 继承于 StatefulWidget,通过 State 的 build 方法去构建控件*/class DemoRefreshListView extends StatefulWidget {通过构造方法传值DemoRefreshListView();//主要是负责创建state@override_DemoStateWidgetState createState() => _DemoStateWidgetState();}/*** 在 State 中,可以动态改变数据* 在 setState 之后,改变的数据会触发 Widget 重新构建刷新*/class _DemoStateWidgetState extends State<DemoRefreshListView>with SingleTickerProviderStateMixin {_DemoStateWidgetState();//ListView 数据源List list = new List();//ScrollController可以监听滑动事件,判断当前view所处的位置ScrollController _scrollController = ScrollController();//分页 加载的页数int _page = 1;//是否正在加载数据bool isLoading = false;@overridevoid initState() {///初始化,这个函数在生命周期中只调用一次super.initState();//初始化模拟数据list = List.generate(15, (i) => '哈喽,我是原始数据 $i');//设置监听_scrollController.addListener(() {if (_scrollController.position.pixels ==_scrollController.position.maxScrollExtent) {print('滑动到了最底部');_getMore();}});}@overridevoid didChangeDependencies() {///在initState之后调 Called when a dependency of this [State] object changes.super.didChangeDependencies();}@overrideWidget build(BuildContext context) {return new Scaffold(appBar: new AppBar(// Here we take the value from the MyHomePage object that was created by// the App.build method, and use it to set our appbar title.title: new Text("list"),),body: RefreshIndicator(//下拉刷新触发方法onRefresh: _onRefresh,//设置listViewchild: ListView.builder(//条目显示布局itemBuilder: _renderRow,//listView 的控制器controller: _scrollController,//条目个数据 这里+1 是最后一条目显示 加载更多提示itemCount: list.length+1,),),);}Widget _renderRow(BuildContext context, int index) {if (index < list.length) {return ListTile(title: Text(list[index]),);}return _getMoreWidget();}/*** 下拉刷新方法,为list重新赋值*/Future<Null> _onRefresh() async {await Future.delayed(Duration(seconds: 1), () {print('refresh');setState(() {list = List.generate(20, (i) => '哈喽,我是新刷新的 $i');});});}/*** 上拉加载更多*/Future _getMore() async {if (!isLoading) {setState(() {isLoading = true;});await Future.delayed(Duration(seconds: 1), () {print('加载更多');setState(() {list.addAll(List.generate(5, (i) => '第$_page次上拉来的数据'));_page++;isLoading = false;});});}}/*** 加载更多时显示的组件,给用户提示*/Widget _getMoreWidget() {return Center(child: Padding(padding: EdgeInsets.all(10.0),child: Row(mainAxisAlignment: MainAxisAlignment.center,crossAxisAlignment: CrossAxisAlignment.center,children: <Widget>[Text('加载中...',style: TextStyle(fontSize: 16.0),),CircularProgressIndicator(strokeWidth: 1.0,)],),),);}@overridevoid dispose() {// TODO: implement disposesuper.dispose();_scrollController.dispose();}}
本公众号会首发系列专题文章,付费的视频课程会在公众号中免费刊登,在你上下班的路上或者是睡觉前的一刻,本公众号都是你浏览知识干货的一个小选择,收藏不如行动,在那一刻,公众号会提示你该学习了。
【##】目前在西瓜视频上免费刊登 Flutter 系列教程,每日更新,欢迎关注接收提醒点击查看提示