Flutter页面如何实现滚动分页加载API返回的1000+条数据功能?
Flutter 分页加载功能实现方案
核心改动说明
你现在的代码是一次性拉取全量1000条数据后全量渲染,我们只需要加滚动监听、分段展示即可实现需求,不需要调整接口请求逻辑,修改步骤如下:
- 新增状态变量存储全量数据、当前展示数量、滚动控制器
- 监听滚动事件,滚动到底部时自动追加展示下一批20条数据
- 列表底部新增加载状态提示
修改后完整代码
class Status extends StatefulWidget { Status({Key key, this.title}) : super(key: key); String title; @override _StatusState createState() => _StatusState(); } class _StatusState extends State<Status> with AutomaticKeepAliveClientMixin{ ObdApi obdApi = ObdApi(); // 新增状态变量 List<dynamic> _allObdList = []; // 存储接口返回的全量obd数据,类型替换成你实际的Obd实体类类型 int _currentShowCount = 20; // 初始展示20条 final ScrollController _scrollController = ScrollController(); bool _isLoadingMore = false; @override bool get wantKeepAlive => true; @override void initState() { super.initState(); // 监听滚动事件 _scrollController.addListener(() { // 滚动到距离底部不足100像素时触发加载更多 if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent - 100) { _loadMoreData(); } }); } // 加载更多逻辑 void _loadMoreData() async { if (_isLoadingMore || _currentShowCount >= _allObdList.length) return; setState(() { _isLoadingMore = true; }); // 模拟加载延迟,不需要可以删掉 await Future.delayed(const Duration(milliseconds: 300)); setState(() { // 每次追加20条,不足20条就取剩下的所有 _currentShowCount += 20; if (_currentShowCount > _allObdList.length) { _currentShowCount = _allObdList.length; } _isLoadingMore = false; }); } @override void dispose() { _scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { super.build(context); return SafeArea( minimum: const EdgeInsets.all(10.0), child: Scaffold( backgroundColor: Colors.white, body: Container( child: FutureBuilder<ActiveObd>( future: obdApi.getActiveObd(), builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: return const Text('no connection'); case ConnectionState.active: case ConnectionState.waiting: return const Center( child: CircularProgressIndicator(), ); case ConnectionState.done: if (snapshot.hasError) { return const Center( child: CircularProgressIndicator(), ); } else { if (snapshot.hasData) { // 接口返回后把全量数据存到状态变量里 if (_allObdList.isEmpty) { _allObdList = snapshot.data.obds; } return ListView.builder( controller: _scrollController, // 总长度是当前展示数量 + 1(最后一位放加载指示器) itemCount: _currentShowCount < _allObdList.length ? _currentShowCount + 1 : _currentShowCount, itemBuilder: (context , index){ // 渲染加载指示器 if (index == _currentShowCount) { return const Padding( padding: EdgeInsets.symmetric(vertical: 16), child: Center( child: CircularProgressIndicator(strokeWidth: 2), ), ); } final obd = _allObdList[index]; DateTime date = DateTime.parse(obd.dateOBDCommand); String result = DateFormat('yyyy-MM-dd H:m:s').format(date); return Card( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ ListTile( title: Container( height: 30, child: Text("${obd.description}") ), subtitle: Text(result.toString()), trailing: Text("${obd.value}"), ) ], ), ); } ); } else { return const Text('No Data'); } } default: return Container(); } } ) ) ) ); } }
可选优化方案
如果你的后端接口支持分页请求(传page、pageSize参数返回对应批次的数据),可以把上面的逻辑改成每次滚动到底部再请求下一页接口,能减少首次加载等待时间,只需要调整_loadMoreData方法里的逻辑,把追加展示数量改成请求下一页接口,把返回的数据拼到_allObdList里即可。
内容的提问来源于stack exchange,提问作者lucky
相关产品推荐
相关产品推荐

