如何在Flutter中从Firebase缓存图像?

问题描述 投票:0回答:1

我正在尝试访问Firebase存储中的图像并将其本地缓存在设备上。

我当前的尝试使用flutter_cache_manager。该文档指出:

最常见的文件服务将是[HttpFileService],但是也可以使某些服务更加专业。例如,您可以从其他应用程序或本地存储中获取文件。

class HttpFileService implements FileService {
  http.Client _httpClient;
  HttpFileService({http.Client httpClient}) {
    _httpClient = httpClient ?? http.Client();
  }

  @override
  Future<FileServiceResponse> get(String url,
      {Map<String, String> headers = const {}}) async {
    final req = http.Request('GET', Uri.parse(url));
    req.headers.addAll(headers);
    final httpResponse = await _httpClient.send(req);

return HttpGetResponse(httpResponse);

  }
}

我尝试扩展此类以处理Firebase的URL

class FirebaseHttpFileService extends HttpFileService {
  @override
  Future<FileServiceResponse> get(String url, {Map<String, String> headers = const {}}) async {

    var ref = FirebaseStorage.instance.ref().child(url);
    var _url = await ref.getDownloadURL() as String;

    return super.get(_url);
  }
}

并使用GitHub repo中的模板扩展BaseCacheManager,将文件服务替换为我的新文件服务。

class FirebaseCacheManager extends BaseCacheManager {
  static const key = "firebaseCache";

  static FirebaseCacheManager _instance;

  factory FirebaseCacheManager() {
    if (_instance == null) {
      _instance = new FirebaseCacheManager._();
    }
    return _instance;
  }

  FirebaseCacheManager._() : super(key,
      maxAgeCacheObject: Duration(days: 7),
      maxNrOfCacheObjects: 20,
      fileService: FirebaseHttpFileService());

  Future<String> getFilePath() async {
    var directory = await getTemporaryDirectory();
    return p.join(directory.path, key);
  }
}

但出现以下错误:

setState() called after dispose(): _ImageState#50d41(lifecycle state: defunct, not mounted, stream: ImageStream#ac6d5(MultiFrameImageStreamCompleter#0c956, [2448×3264] @ 1.0x, 3 listeners), pixels: null, loadingProgress: null, frameNumber: null, wasSynchronouslyLoaded: false)

我可以在尝试检索文件之前处理URL,但这不必要地浪费时间。我也尝试过使用Flutter Cache Image之类的其他程序包,但似乎在短时间内使应用程序崩溃。

感谢任何正确方向的指针!

firebase flutter dart firebase-storage flutter-dependencies
1个回答
0
投票

实际上,此问题与errorWidget有关,如问题here所示。如果错误小部件在CachedNetworkImage中被注释掉,则该代码有效。

© www.soinside.com 2019 - 2024. All rights reserved.