skip to Main Content

I am practicing my API calls in Flutter. Now, I want to implement caching for these API calls on a monthly basis. The caching process should occur initially when the JSON data is fetched for the first time. Then, from the beginning to the end of each month, the cached data should be used. At the start of a new month, the cache should be refreshed with updated JSON data. How can I achieve this?

I am using SQFlite. But any other database solution is welcome here.

class PrayerTimesApi {
  static Future<void> fetchAndStorePrayerTimes() async {
    String url = 'example.com';

    var response = await http.post(
      Uri.parse(url),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
    );

    if (response.statusCode == 200) {
      Map<String, dynamic> responseData = jsonDecode(response.body);
      List<dynamic> prayerTimesData = responseData['prayerTimes'];

    
      String currentDate =
          DateFormat('EEEE dd MMMM yyyy').format(DateTime.now());

      Map<String, dynamic>? currentPrayerTimes;
      for (var prayerTime in prayerTimesData) {
        if (prayerTime['date'] == currentDate) {
          currentPrayerTimes = prayerTime;
          break;
        }
      }

      if (currentPrayerTimes != null) {
        
        PrayerTimes prayerTimes = PrayerTimes.fromJson(currentPrayerTimes);

        await LocalDatabase.insertPrayerTimes(prayerTimes);
      } else {
        throw 'Not available for $currentDate.';
      }
    } else {
      throw 'Failed to fetch.';
    }
  }
}

2

Answers


  1. You can store the response data with timestamp mapped.
    On app startup, Compare the data download month and current month, refresh if not match.

    For storing the response, either you can use local file system, or another approach could be NoSql Database Hive (https://pub.dev/packages/hive)

    Login or Signup to reply.
  2. There are multiple ways you can cache your data based on data size ,

    shared_preferences: ^2.2.2
    sqflite: ^2.3.2
    hive: ^2.2.3

    I would prefer the Local Databases Sqflite and Hive , with these you cache your data and use a timer for one month or use updateAt value from the api and based on that value check you can update the localdb and then make the Api call after one month,whenever the Api gets called the local db will be updated . For more concern you can ask.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search