【问题标题】:Flutter Image loading and cachingFlutter 图像加载和缓存
【发布时间】:2019-10-01 03:58:21
【问题描述】:
这是我的用例:
- 我正在获取图片的 URL 列表。
- 我想在数据库中显示和缓存它们,而不仅仅是针对特定会话,因此下次它不应该调用 Web 服务。
我们的应用也可以离线运行。我尝试了一些库,例如 flutter_advanced_networkimage 和 flutter_cache_manager,但我的速度很慢,而且大多数时候应用程序崩溃。
【问题讨论】:
标签:
image
caching
flutter
cache-control
【解决方案1】:
将其保存在应用的临时目录中:
import 'dart:io';
// https://pub.dev/packages/path_provider
import 'package:path_provider/path_provider.dart';
final Directory temp = await getTemporaryDirectory();
final File imageFile = File('${temp.path}/images/someImageFile.png');
if (await imageFile.exists()) {
// Use the cached images if it exists
} else {
// Image doesn't exist in cache
await imageFile.create(recursive: true);
// Download the image and write to above file
...
}
它会在应用启动时持续存在,并且只有在用户亲自清除缓存或重新安装应用时才会被删除。
【解决方案3】:
如果你想兑现图像或从 API 检索到的任何字段,你可以使用 SharedPref 包
在您的 pubspec.yame 中:
shared_preferences: ^2.0.5 . // use latest version
这里是 SharedPref 类:
class AppSharedPref {
static const String KEY_STAFF_AVATAR = "Avatar";
static setString(String key, String value) async {
final sp = await SharedPreferences.getInstance();
sp.setString(key, value);
}
static Future<String?> getString(String key) async {
final sp = await SharedPreferences.getInstance();
return sp.getString(key) == null ? "" : sp.getString(key);
}
}
你可以这样兑现:
AppSharedPref.setString(AppSharedPref.KEY_STAFF_AVATAR, "$UrlFromAPIResponse");
然后像这样检索它:
String photoURL ='';
AppSharedPref.getString(AppSharedPref.KEY_STAFF_AVATAR).then((value) {
photoURL = value!;
});
在您的小部件中使用 photoURL:
Image.network(photoURL);
或
NetworkImage(photoURL);