Files
submanager/lib/services/exchange_rate_service.dart
JiWoong Sul 83c5e3d64e Refactor screens to MVC architecture with modular widgets
- Extract business logic from screens into dedicated controllers
- Split large screen files into smaller, reusable widget components
- Add controllers for AddSubscriptionScreen and DetailScreen
- Create modular widgets for subscription and detail features
- Improve code organization and maintainability
- Remove duplicated code and improve reusability

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-11 00:21:18 +09:00

92 lines
2.7 KiB
Dart

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:intl/intl.dart';
/// 환율 정보 서비스 클래스
class ExchangeRateService {
// 싱글톤 인스턴스
static final ExchangeRateService _instance = ExchangeRateService._internal();
// 팩토리 생성자
factory ExchangeRateService() {
return _instance;
}
// 내부 생성자
ExchangeRateService._internal();
// 캐싱된 환율 정보
double? _usdToKrwRate;
DateTime? _lastUpdated;
// API 요청 URL (ExchangeRate-API 사용)
final String _apiUrl = 'https://api.exchangerate-api.com/v4/latest/USD';
/// 현재 USD to KRW 환율 정보를 가져옵니다.
/// 최근 6시간 이내 조회했던 정보가 있다면 캐싱된 정보를 반환합니다.
Future<double?> getUsdToKrwRate() async {
// 캐싱된 데이터 있고 6시간 이내면 캐싱된 데이터 반환
if (_usdToKrwRate != null && _lastUpdated != null) {
final difference = DateTime.now().difference(_lastUpdated!);
if (difference.inHours < 6) {
return _usdToKrwRate;
}
}
try {
// API 요청
final response = await http.get(Uri.parse(_apiUrl));
if (response.statusCode == 200) {
final data = json.decode(response.body);
_usdToKrwRate = data['rates']['KRW'].toDouble();
_lastUpdated = DateTime.now();
return _usdToKrwRate;
} else {
// 실패 시 캐싱된 값이라도 반환
return _usdToKrwRate;
}
} catch (e) {
// 오류 발생 시 캐싱된 값이라도 반환
return _usdToKrwRate;
}
}
/// USD 금액을 KRW로 변환합니다.
Future<double?> convertUsdToKrw(double usdAmount) async {
final rate = await getUsdToKrwRate();
if (rate != null) {
return usdAmount * rate;
}
return null;
}
/// 현재 환율 정보를 포맷팅하여 텍스트로 반환합니다.
Future<String> getFormattedExchangeRateInfo() async {
final rate = await getUsdToKrwRate();
if (rate != null) {
final formattedRate = NumberFormat.currency(
locale: 'ko_KR',
symbol: '',
decimalDigits: 0,
).format(rate);
return '오늘 기준 환율 : $formattedRate';
}
return '';
}
/// USD 금액을 KRW로 변환하여 포맷팅된 문자열로 반환합니다.
Future<String> getFormattedKrwAmount(double usdAmount) async {
final krwAmount = await convertUsdToKrw(usdAmount);
if (krwAmount != null) {
final formattedAmount = NumberFormat.currency(
locale: 'ko_KR',
symbol: '',
decimalDigits: 0,
).format(krwAmount);
return '($formattedAmount)';
}
return '';
}
}