Flutter健身房列表API缓存实现:离线加载功能开发求助
健身房列表页离线缓存功能实现
前置依赖准备
要实现网络状态检测、本地文件读写能力,需要先在项目pubspec.yaml中引入如下依赖,执行flutter pub get完成安装:
connectivity_plus:用于检测设备当前的网络连接状态path_provider:用于获取应用专属的可读写本地缓存目录
核心实现逻辑
完全基于现有代码框架改造,不改动原有列表UI的渲染逻辑,仅调整数据加载流程匹配需求:
- 有网场景:页面触发数据加载时,先调用线上API拉取最新健身房原始JSON数据,将完整响应存入本地缓存JSON文件,再解析数据渲染列表
- 无网场景:页面触发数据加载时,跳过线上API请求,直接读取本地存储的缓存JSON文件,解析完成后渲染列表
- 异常兜底:无网且本地无任何缓存文件时,返回明确的错误提示,避免页面白屏
改造后的完整代码
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'dart:io'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:path_provider/path_provider.dart'; class GymList extends StatefulWidget { const GymList({super.key}); @override State<GymList> createState() => _GymListState(); } class _GymListState extends State<GymList> { final String apiUrl = "apitogetgyms"; // 获取本地缓存文件路径 Future<File> _getCacheFile() async { final appCacheDir = await getApplicationCacheDirectory(); return File('${appCacheDir.path}/gym_cache.json'); } // 将拉取到的原始JSON写入本地缓存 Future<void> _saveCache(String rawJson) async { final cacheFile = await _getCacheFile(); await cacheFile.writeAsString(rawJson); } // 读取本地缓存的JSON内容 Future<String> _readCache() async { final cacheFile = await _getCacheFile(); if (!await cacheFile.exists()) { throw "暂无本地缓存数据,请连接网络后打开页面加载"; } return await cacheFile.readAsString(); } // 检测当前网络是否可用 Future<bool> _checkNetworkAvailable() async { final connectivityResult = await Connectivity().checkConnectivity(); return !connectivityResult.contains(ConnectivityResult.none); } Future<List<dynamic>> fetchGyms() async { final isNetworkAvailable = await _checkNetworkAvailable(); String rawResponseJson; if (isNetworkAvailable) { // 有网络时拉取线上数据并更新缓存 final result = await http.get(Uri.parse(apiUrl)); rawResponseJson = result.body; await _saveCache(rawResponseJson); } else { // 无网络时读取本地缓存 rawResponseJson = await _readCache(); } return json.decode(rawResponseJson)['gyms']; } String _name(dynamic gyms) => gyms['name']; String _location(dynamic gyms) => gyms['location']; String _phone(dynamic gyms) => gyms['phone']; String _email(dynamic gyms) => gyms['email']; String _img(dynamic gyms) => gyms['img']; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Gyms List'), ), body: Container( child: FutureBuilder<List<dynamic>>( future: fetchGyms(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { return ListView.builder( padding: const EdgeInsets.all(8), itemCount: snapshot.data.length, itemBuilder: (BuildContext context, int index) { return Card( child: Column( children: <Widget>[ ListTile( leading: CircleAvatar( radius: 30, backgroundImage: NetworkImage(snapshot.data[index]['img'])), title: Text(_name(snapshot.data[index])), subtitle: Text(_location(snapshot.data[index])), trailing: Text(_email(snapshot.data[index]))), ], ), ); }); } else if (snapshot.hasError) { return Center(child: Text("${snapshot.error}")); } else { return const Center(child: CircularProgressIndicator()); } }, ), ), ); } }
补充说明:上述代码仅实现了健身房列表基础文本信息的离线展示,列表中引用的图片仍为网络加载,若需要实现图片完全离线可用,可后续补充图片资源的本地持久化缓存逻辑。
内容的提问来源于stack exchange,提问作者kevin ongulu
相关产品推荐
相关产品推荐

