Files
rental_income_tracker/lib/services/open_exchange_service.dart
T
hans f050d10a1d Initial commit
Signed-off-by: Hans Kokx <hans.d.kokx@gmail.com>
2026-03-19 20:29:22 +01:00

39 lines
1.1 KiB
Dart

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();
}
}