I have done various ways to create a cached product list then display with a list, but till now still not working, can anyone help me
My Json fromCache
"[{"id":"2911","nama":"Abcd1","url":"myUrl"},{"id":"2910","nama":"Abcd2","url":"myUrl"},{"id":"2911","nama":"Abcd3","url":"myUrl"},{"id":"2549","nama":"Abcd4","url":"myUrl"}]"
My Code
Future<List<ApiBookmark>> fetchApiBookmark() async {
var adaCache = await APICacheManager().isAPICacheKeyExist('bookmark');
if (adaCache) {
print('ada');
var cacheData = await APICacheManager().getCacheData('bookmark');
var fromCache = '[' cacheData.syncData ']';
List jsonResponse = fromCache as List;
return jsonResponse
.map((e) => ApiBookmark(id: e.id, nama: e.nama, url: e.url))
.toList();
} else {
print('tidak ada');
throw Exception('Failed to load bookmark');
}
}
class ApiBookmark {
final String id;
final String nama;
final String url;
const ApiBookmark({
required this.id,
required this.nama,
required this.url,
});
factory ApiBookmark.fromJson(Map<String, dynamic> json) {
return ApiBookmark(
id: json['id'],
nama: json['nama'],
url: json['url'],
);
}
}
CodePudding user response:
Try this
List<ApiBookmark> listApi = <ApiBookmark>[];
Future<List<ApiBookmark>> fetchApiBookmark() async {
listApi.clear();
var fromCache = '''[{"id":"2911","nama":"Abcd1","url":"myUrl"},
{"id":"2910","nama":"Abcd2","url":"https://sim.saktiputra.com/api/produk/detail/2910/1"},
{"id":"2911","nama":"Abcd3","url":"myUrl"},
{"id":"2549","nama":"Abcd4","url":"myUrl"}]''';
final jsonData = json.decode(fromCache);
for (var item in jsonData) {
listApi.add(ApiBookmark.fromJson(item));
}
for (var item in listApi) {
print("${item.id} ${item.nama} ${item.url}");
}
return listApi;
}
then you can implement "APICacheManager()"