gpt4 book ai didi

flutter - 如何在Flutter中缓存API调用的响应?

转载 作者:行者123 更新时间:2023-12-03 13:29:10 33 4
gpt4 key购买 nike

我正在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'];
} }

请帮我解决这个问题。

最佳答案

pubspec.yaml中包括flutter_cache_manager
现在定义一个缓存管理器

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;
}
}
现在使用
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);
}
}
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

There is no longer a need to extend on BaseCacheManager, you can directly call the constructor. The BaseCacheManager is now only an interface. CacheManager is the implementation you can use directly.


检查 here

关于flutter - 如何在Flutter中缓存API调用的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60108286/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com