Flutter之下拉刷新,上拉加载更多

Flutter之下拉刷新,上拉加载更多

// 下拉刷新,上拉加载更多 class PullAndLoadViewDemo extends StatefulWidget { @override State createState() => _PullAndLoadViewDemo(); }class _PullAndLoadViewDemo extends State【Flutter之下拉刷新,上拉加载更多】 { List sourceData = https://www.it610.com/article/[]; // 当前页数 int _currentPage = 1; // 总页数 int _totalPage = 3; // 每页数据条数 int _pageCount = 20; // 是否加载中 bool isLoading = false; // 滑动控制器 ScrollController _scrollController = ScrollController(); @override void initState() { super.initState(); _scrollController.addListener(() { // 实现预加载 double edge = 50.0; if (_scrollController.position.maxScrollExtent - _scrollController.position.pixels <= edge) { // 加载更多 _loadMore(); } }); _refreshData(); }@override void dispose() { super.dispose(); _scrollController.dispose(); }@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("列表刷新案例"), ), body: RefreshIndicator( child: ListView.builder( itemBuilder: (context, index) { return _generateListItemView(index); }, itemCount: _getItemCount(), controller: _scrollController, // 保持任何情况下都能滚动 physics: const AlwaysScrollableScrollPhysics(), ), onRefresh: _refreshData), ); }// 下拉刷新数据 Future _refreshData() async { await Future.delayed(Duration(seconds: 2), () { setState(() { _currentPage = 1; sourceData.clear(); sourceData.addAll(List.generate(_pageCount, (index) => "我是刷新后据$index")); }); }); }// 上拉加载更多数据 Future _loadMore() async { if (!isLoading) { setState(() { isLoading = true; }); await Future.delayed(Duration(seconds: 2), () { setState(() { _currentPage++; if (_currentPage < _totalPage) { sourceData.addAll(List.generate( _pageCount, (index) => "加载更多:页数$_currentPage,条数$index")); } else if (_currentPage == _totalPage) { //TODO 模拟最后一页数据 sourceData.addAll(List.generate( _pageCount - 5, (index) => "加载更多:页数$_currentPage,条数$index")); } isLoading = false; }); }); } }int _getItemCount() { if (sourceData.length == 0) { return 0; } return sourceData.length + 1; }Widget _generateListItemView(index) { if (_currentPage >= _totalPage && index == sourceData.length) { return _loadMoreFinishedWidget(); } if (index < sourceData.length) { return ListTile( title: Text(sourceData[index]), ); } return _loadMoreDateWidget(); } // 加载完成 Widget _loadMoreFinishedWidget() { return Center( child: Padding( padding: EdgeInsets.all(10.0), child: Text( "没有更多数据了", style: TextStyle(fontSize: 16.0), ), ), ); }// 加载中... Widget _loadMoreDateWidget() { return Center( child: Padding( padding: EdgeInsets.all(10.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox( width: 30.0, height: 30.0, child: CircularProgressIndicator( strokeWidth: 1.0, ), ), Padding(padding: EdgeInsets.all(10.0)), Text( "加载中....", style: TextStyle(fontSize: 16.0), ), ], ), ), ); } }

    推荐阅读