I have an issue with fetching data from API, my goal is to get separated data like only dates and only values of currency. Basically at some point in trying to solve this problem I've got dates as keys but couldn't get the values of currency. Now I'm getting only nulls.
{
"base": "EUR",
"end_date": "2020-06-06",
"rates": {
"2020-06-01": {
"USD": 1.112558
},
"2020-06-02": {
"USD": 1.118756
},
"2020-06-03": {
"USD": 1.123471
},
"2020-06-04": {
"USD": 1.133657
},
"2020-06-05": {
"USD": 1.129095
},
"2020-06-06": {
"USD": 1.12915
}
},
"start_date": "2020-06-01",
"success": true,
"timeseries": true
}
import 'dart:convert';
import 'package:currency_exchange/models/currency.dart';
import 'package:currency_exchange/models/rate_timeseries.dart';
class CurrencyTimeseries {
CurrencyTimeseries({
required this.base,
required this.endDate,
required this.rates,
required this.startDate,
required this.success,
required this.timeseries,
});
Currency base;
DateTime endDate;
Rate rates;
DateTime startDate;
bool success;
bool timeseries;
factory CurrencyTimeseries.fromJson(
Map<String, dynamic> json, Currency symbol) =>
CurrencyTimeseries(
base: Currency.values
.firstWhere((element) => element.name == json['base']),
endDate: DateTime.parse(json["end_date"]),
rates: Rate.fromJson(json["rates"]),
success: json["success"] == "true",
startDate: DateTime.parse(json["start_date"]),
timeseries: json["timeseries"],
);
}
import 'dart:convert';
class Rate {
Rate({
required this.eur,
});
double eur;
factory Rate.fromJson(Map<String, dynamic> json) => Rate(
eur: json["EUR"],
);
}
Future<CurrencyTimeseries> fetchTimeseries(
Currency base,
DateTime endDate,
DateTime startDate,
Currency symbol,
) async {
RequestOptions req = RequestOptions(
path: '/timeseries',
queryParameters: {
'base': base.name,
'end_date': DateFormat('yyyy-MM-dd').format(endDate),
'start_date': DateFormat('yyyy-MM-dd').format(startDate),
'symbols': symbol.name,
},
baseUrl: _apiUrl,
headers: {'apikey': _apiKey},
method: 'GET',
);
Response response = await _dio.fetch(req);
print(response.data);
return CurrencyTimeseries.fromJson(
response.data,
symbol,
);
}
This is how to access rates:
final startDate = json["start_date"];
final endDate = json["end_date"];
final startDateUSD = json["rates"][startDate]["USD"];
...
final endDateUSD = json["rates"][endDate]["USD"];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.