53 lines
2.0 KiB
Dart
53 lines
2.0 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:wetter/models/daily_weather_model.dart';
|
|
|
|
class BrightSkyAPI {
|
|
static Future<DailyWeatherModel> fetchForecastOfSingleDay(DateTime d) async {
|
|
String dt = "${d.year}-${d.month}-${d.day}";
|
|
final response = await http.get(
|
|
Uri.parse(
|
|
'https://api.brightsky.dev/weather?lat=53.43&lon=10&date=$dt&tz=Europe/Berlin'),
|
|
headers: {"Accept": "application/json"});
|
|
if (response.statusCode == 200) {
|
|
return DailyWeatherModel.fromJson(jsonDecode(response.body));
|
|
} else {
|
|
throw Exception('Failed to load weather data');
|
|
}
|
|
}
|
|
|
|
static Future<List<DailyWeatherModel>> fetchForecastForTimeRange(
|
|
DateTime from, DateTime until) async {
|
|
String fromDay = "${from.year}-${from.month}-${from.day}";
|
|
String untilDay = "${until.year}-${until.month}-${until.day}";
|
|
final response = await http.get(
|
|
Uri.parse(
|
|
'https://api.brightsky.dev/weather?lat=53.43&lon=10&date=$fromDay&last_date=$untilDay&tz=Europe/Berlin'),
|
|
headers: {"Accept": "application/json"});
|
|
final Map<String, dynamic> responseAsJson = jsonDecode(response.body);
|
|
if (response.statusCode == 200) {
|
|
List<DailyWeatherModel> data = splitRangeToDaily(responseAsJson);
|
|
return data;
|
|
} else {
|
|
throw Exception('Failed to load weather data');
|
|
}
|
|
}
|
|
|
|
static List<DailyWeatherModel> splitRangeToDaily(Map<String, dynamic> json) {
|
|
List dataPoints = json['weather'];
|
|
List<DailyWeatherModel> response = [];
|
|
Map<String, dynamic> currPoint = {"weather": []};
|
|
String currDay = dataPoints[0]['timestamp'].substring(0, 10);
|
|
for (var point in dataPoints) {
|
|
if (currDay != point['timestamp'].substring(0, 10)) {
|
|
currDay = point['timestamp'].substring(0, 10);
|
|
response.add(DailyWeatherModel.fromJson(currPoint));
|
|
currPoint = {"weather": []};
|
|
} else {
|
|
currPoint['weather'].add(point);
|
|
}
|
|
}
|
|
return response;
|
|
}
|
|
}
|