Flutter 如何缓存 API 调用的响应?

Phi*_*raj 9 flutter

我在 Flutter App 中工作以从 API 获取项目。我想将 API 响应缓存 12 小时。响应将每 12 小时更改一次。12 小时完成后,我需要从 Internet 获取它。我使用下面的代码从互联网上获取它。

Future<List<Playlist>> fetchPlaylistByChannelId({String channelId}) async {
Map<String, String> parameters = {
  'part': 'snippet,contentDetails',
  'channelId': channelId,
  'maxResults': '10',
  'key': API_KEY,
};
Uri uri = Uri.https(
  _baseUrl,
  '/youtube/v3/playlists',
  parameters,
);
Map<String, String> headers = {
  HttpHeaders.contentTypeHeader: 'application/json',
};

// Get Playlist details
var response = await http.get(uri, headers: headers);
if (response.statusCode == 200) {
  var data = json.decode(response.body);
  List<dynamic> playListJson = data['items'];

  // Fetch all play list
  List<Playlist> playLists = [];
  playListJson.forEach(
    (json) => playLists.add(
      Playlist.fromMap(
        json["id"],
        json["snippet"],
        json["contentDetails"],
      ),
    ),
  );
  return playLists;
} else {
  throw json.decode(response.body)['error']['message'];
}   }
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题。

Dev*_*Dev 9

flutter_cache_manager包含在pubspec.yaml.

现在定义一个缓存管理器

import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

// Custom Implementation of CacheManager
// by extending the BaseCacheManager abstract class
class MyCacheManager extends BaseCacheManager {
  static const key = "customCache";

  static MyCacheManager _instance;

  // singleton implementation 
  // for the custom cache manager
  factory MyCacheManager() {
    if (_instance == null) {
      _instance = new MyCacheManager._();
    }
    return _instance;
  }

  // pass the default setting values to the base class
  // link the custom handler to handle HTTP calls 
  // via the custom cache manager
  MyCacheManager._()
      : super(key,
            maxAgeCacheObject: Duration(hours: 12),
            maxNrOfCacheObjects: 200,
            fileFetcher: _myHttpGetter);

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

  static Future<FileFetcherResponse> _myHttpGetter(String url,
      {Map<String, String> headers}) async {
    HttpFileFetcherResponse response;
    // Do things with headers, the url or whatever.
    try {
      var res = await http.get(url, headers: headers);
      // add a custom response header
      // to regulate the caching time
      // when the server doesn't provide cache-control
      res.headers.addAll({'cache-control': 'private, max-age=120'});
      response = HttpFileFetcherResponse(res);
    } on SocketException {
      print('No internet connection');
    }
    return response;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在使用

class HttpProvider {
  Future<Response> getData(String url, Map<String, String> headers) async {
    var file = await MyCacheManager().getSingleFile(url, headers: headers);
    if (file != null && await file.exists()) {
      var res = await file.readAsString();
      return Response(res, 200);
    }
    return Response(null, 404);
  }
}
Run Code Online (Sandbox Code Playgroud)

详情见https://referbruv.com/blog/posts/caching-get-request-calls-using-flutter-cache-managerhttps://proandroiddev.com/flutter-lazy-loading-data-from-network- with-caching-b7486de57f11


更新:flutter_cache_manager 2.0.0

BaseCacheManager 上不再需要扩展,直接调用构造函数即可。BaseCacheManager 现在只是一个接口。CacheManager 是您可以直接使用的实现。

在这里检查

  • @PhilipJebaraj flutter_cache_manager 使用 SQLite。如果您已经在 Flutter 应用程序中使用 SQLite,请小心。我记得读到过,如果 Flutter 应用程序打开两个 SQLite 数据库,它可能会遇到麻烦。因此,您应该配置 flutter_cache_manager 以使用您的应用程序使用的相同 SQLite 数据库。 (4认同)