How to Cache JSON from REST API in Flutter: A Comprehensive Guide
Introduction
Flutter is a popular open-source mobile app development framework created by Google. It provides a wide range of benefits, including fast development, good performance, and native-like experience. When building a Flutter app, you often need to fetch data from a REST API. However, frequently making API calls can lead to slower performance and higher network costs. This is where caching comes into play. In this article, we’ll explore how to cache JSON data from a REST API in Flutter using the package `http` and the library `shared_preferences`.
Need for Caching
Caching is a technique of storing frequently accessed data in a local storage to reduce the number of requests to the server. In the context of REST APIs, caching is essential for:
- Reducing network latency and improving app performance
- Minimizing the cost of making API calls
- Providing a better user experience
Choosing a Caching Library
Flutter provides several caching libraries, including `cachednetworkimage`, `cachednetworkimagememorycache`, and `sharedpreferences`. For this article, we’ll use `sharedpreferences` due to its simplicity and wide adoption.
Getting Started with Caching
Before we dive into the code, make sure to add the required packages to your `pubspec.yaml`:
“`yml
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
shared_preferences: ^2.1.0
“`
Run `flutter pub get` to install the packages.
Caching JSON Data
Here’s an example of how to cache JSON data from a REST API using `http` and `shared_preferences`:
“`dart
import ‘package:flutter/material.dart’;
import ‘package:http/http.dart’ as http;
import ‘dart:convert’;
import ‘package:sharedpreferences/sharedpreferences.dart’;
class JsonCache {
static const prefKey = ‘jsoncache’;
static Future
final prefs = await SharedPreferences.getInstance();
final data = prefs.getString(_prefKey);
if (data != null) {
return jsonDecode(data);
}
return null;
}
static Future
final prefs = await SharedPreferences.getInstance();
final jsonString = jsonEncode(data);
await prefs.setString(_prefKey, jsonString);
}
static Future
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
// cache the response
cacheJson(url, jsonDecode(response.body));
return jsonDecode(response.body);
} else {
return null;
}
} catch (e) {
print(e);
return null;
}
}
}
“`
Usage Example
To use the `JsonCache` class, simply call the `fetchData` method and store the result in a variable. If the data is cached, the function will return the cached result instead of making a network request.
“`dart
void main() async {
final url = ‘https://jsonplaceholder.typicode.com/posts’;
final cachedData = await JsonCache.getCache();
if (cachedData != null) {
print(cachedData);
} else {
final jsonData = await JsonCache.fetchData(url);
print(jsonData);
await JsonCache.cacheJson(url, jsonData);
}
}
“`
Conclusion
Caching JSON data from a REST API is a crucial technique for improving app performance and reducing network costs. In this article, we’ve explored how to cache JSON data using the `http` package and the `shared_preferences` library. By following the examples and code provided, you can easily implement caching in your Flutter app.
FAQs
Q: Why should I cache JSON data from a REST API?
A: Caching reduces network latency, minimizes API call costs, and provides a better user experience.
Q: What is the difference between `cachednetworkimage` and `shared_preferences`?
A: `cachednetworkimage` is a library for caching images, while `shared_preferences` is a library for caching generic data.
Q: How do I check if data is cached before making a network request?
A: You can check if data is cached by calling the `getCache` method and checking if the result is not null.
Q: Can I use `shared_preferences` to cache data other than JSON?
A: Yes, you can store any type of data in `shared_preferences`, not just JSON.
Q: Is caching data in `shared_preferences` secure?
A: `shared_preferences` stores data in the app’s local storage, which means it’s not secure and should not be used for sensitive data.