@@ -0,0 +1,38 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
class OpenExchangeService {
|
||||
OpenExchangeService({required this.httpClient, required this.apiKey});
|
||||
|
||||
final http.Client httpClient;
|
||||
final String apiKey;
|
||||
|
||||
Future<double> fetchUsdToSekRate({required DateTime estDate}) async {
|
||||
if (apiKey == 'REPLACE_WITH_YOUR_OPENEXCHANGE_API_KEY') {
|
||||
throw StateError('OpenExchange API key is not configured.');
|
||||
}
|
||||
|
||||
final date = DateFormat('yyyy-MM-dd').format(estDate);
|
||||
final uri = Uri.https(
|
||||
'openexchangerates.org',
|
||||
'/api/historical/$date.json',
|
||||
<String, String>{'app_id': apiKey, 'symbols': 'SEK'},
|
||||
);
|
||||
|
||||
final response = await httpClient.get(uri);
|
||||
if (response.statusCode != 200) {
|
||||
throw StateError('OpenExchange request failed (${response.statusCode}).');
|
||||
}
|
||||
|
||||
final json = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
final rates = json['rates'] as Map<String, dynamic>?;
|
||||
final sek = rates?['SEK'];
|
||||
if (sek == null) {
|
||||
throw StateError('SEK rate was missing in API response.');
|
||||
}
|
||||
|
||||
return (sek as num).toDouble();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user