getCurrentWeather method

Future<Map<String, dynamic>?> getCurrentWeather()

Implementation

Future<Map<String, dynamic>?> getCurrentWeather() async {
  try {
    final position = await _determinePosition();
    final url = Uri.parse(
      'https://api.openweathermap.org/data/2.5/weather'
      '?lat=${position.latitude}&lon=${position.longitude}'
      '&units=metric&appid=$_apiKey',
    );

    final response = await http.get(url);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);

      final temp = data['main']?['temp'];
      final description = data['weather']?[0]?['description'];

      if (temp != null && description != null) {
        return {
          'temperature': temp,
          'description': _capitalize(description),
        };
      } else {
        debugPrint("Unexpected weather API format: $data");
        return null;
      }
    } else {
      debugPrint("Weather API error: ${response.statusCode}");
      return null;
    }
  } catch (e) {
    debugPrint("WeatherService error: $e");
    return null;
  }
}