在 Flutter 中保存网络图片以离线加载

sag*_*mar 5 firebase flutter

如何使网络图像在我的应用中离线可用?所以,当我没有网络时,下次可以从缓存中加载它。

我也试过network_to_file_image包和cache network image包,但它对我不起作用。

当我使用缓存网络并且我下次(没有网络)打开应用程序时,图像没有从缓存中再次加载。

这是我在 Flutter 应用程序中使用网络图像包的代码:

CarouselSlider(
          enlargeCenterPage: true,
          autoPlay: true,
          height: 350,
          initialPage: 0,
          items: keyPlans.map((key) {
            File file;
            getData() {
              DirServices().file("loacliamge_${counter++}").then((File data) {
                file = data;
              });
              return file;
            }

            return new CarousalCard(
              image: NetworkToFileImage(file: getData(), url: key, debug: true),
              onPressed: () {
                setState(() {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ImageView(
                                image: CachedNetworkImageProvider(key),
                                text: appTitle,
                              )));
                });
              },
            );
          }).toList());
Run Code Online (Sandbox Code Playgroud)

network_to_file_image 包总是从网络获取数据。

小智 0

包装的临时解决方案cache network image

IOFileSystem将类添加到您的项目中,如此处所述。(希望这个类可以从包中获得,并且我们将来能够删除这个重复的类)

import 'package:file/local.dart';
import 'package:flutter_cache_manager/src/storage/file_system/file_system.dart' as c;
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

class IOFileSystem implements c.FileSystem {
  final Future<Directory> _fileDir;

  IOFileSystem(String key) : _fileDir = createDirectory(key);

  static Future<Directory> createDirectory(String key) async {
    // use documents directory instead of temp
    var baseDir = await getApplicationDocumentsDirectory(); 
    var path = p.join(baseDir.path, key);

    var fs = const LocalFileSystem();
    var directory = fs.directory((path));
    await directory.create(recursive: true);
    return directory;
  }

  @override
  Future<File> createFile(String name) async {
    assert(name != null);
    return (await _fileDir).childFile(name);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后创建CustomCacheManager

import 'package:flutter_cache_manager/flutter_cache_manager.dart';

class CustomCacheManager extends CacheManager with ImageCacheManager {
  static const String key = "customCache";

  static CustomCacheManager _instance;

  factory CustomCacheManager() {
    return _instance ??= CustomCacheManager._();
  }

  CustomCacheManager._()
      : super(Config(key, fileSystem: IOFileSystem(key)),);
}
Run Code Online (Sandbox Code Playgroud)

然后最后将其提供CustomCacheManagerCachedNetworkImage

CachedNetworkImage(
  cacheManager: CustomCacheManager(),
  imageUrl: "your_image_url",
)
Run Code Online (Sandbox Code Playgroud)

那么缓存的文件将不会在会话之间被系统删除