import 'dart:convert'; import 'package:api_cache_manager/api_cache_manager.dart'; import 'package:api_cache_manager/models/cache_db_model.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../model/weather_forecast_model.dart'; import 'package:http/http.dart' as http; class WeatherApiClient { late SharedPreferences sharedPreferences; Future? getCurrentWeather(String? location) async { sharedPreferences = await SharedPreferences.getInstance(); String? tempUnit = sharedPreferences.getString("temp"); // String? unit; String? unit; if (tempUnit != null) { if (tempUnit == "Celsius") { unit = "metric"; } else { unit = "imperial"; } } var endpoint = Uri.parse( "https://api.openweathermap.org/data/2.5/forecast?q=$location&cnt=40&units=$unit&appid=3b4815f56619515169c1cbb39a9eea8f"); var response = await http.get(endpoint); var body = jsonDecode(response.body); WeatherForecast weatherForecast = WeatherForecast.fromJson(body); return weatherForecast; } Future? getCurrentWeatherLocation( double? lat, double? lng) async { var isCacheExist = await APICacheManager().isAPICacheKeyExist("API_WeatherForecast"); if (!isCacheExist) { String? tempUnit = sharedPreferences.getString("temp"); String? unit; if (tempUnit != null) { if (tempUnit == "Celsius") { unit = "metric"; } else { unit = "imperial"; } } else { unit = "metric"; } var endpointLatLong = Uri.parse( "https://api.openweathermap.org/data/2.5/forecast?lat=$lat&lon=$lng&cnt=40&units=$unit&appid=3b4815f56619515169c1cbb39a9eea8f"); var response = await http.get(endpointLatLong); var body = jsonDecode(response.body); WeatherForecast weatherForecast = WeatherForecast.fromJson(body); APICacheDBModel cacheDBModel = APICacheDBModel(key: "API_WeatherForecast", syncData: response.body); await APICacheManager().addCacheData(cacheDBModel); return weatherForecast; } else { var cacheData = await APICacheManager().getCacheData("API_WeatherForecast"); String? tempUnit = sharedPreferences.getString("temp"); var unit; if (tempUnit != null) { if (tempUnit == "Celsius") { unit = "metric"; } else { unit = "imperial"; } } var endpointLatLong = Uri.parse( "https://api.openweathermap.org/data/2.5/forecast?lat=$lat&lon=$lng&cnt=40&units=$unit&appid=3b4815f56619515169c1cbb39a9eea8f"); var response = await http.get(endpointLatLong); // var body = jsonDecode(cacheData.syncData); var body = jsonDecode(response.body); WeatherForecast weatherForecast = WeatherForecast.fromJson(body); return weatherForecast; } } }