여러 가상화폐에 대하여 각국의 화폐에 따른 환율을 제공하는 앱을 만들어야한다.
- 제공할 서비스
BTC, ETH, LTC 가상화폐에 대한 여러 화폐의 환율 제공
원하는 화폐선택
- 해야할것
http & dart:convert 패키지 호출
apiKEY 발급 & api 확인(coinapi.io 사이트 이용)
환율 데이터 가져오기
화면 및 기능구현
https://pub.dev/packages/http
https://api.dart.dev/stable/2.15.1/dart-convert/dart-convert-library.html
import 'dart:convert';
import 'package:http/http.dart' as http;
pubspec.yami
파일dependencies:
http: ^0.13.4
※변경 후 pubget 클릭할것※
https://docs.coinapi.io/?shell#exchange-rates
사이트에서 간단히 apiKEY를 발급받을 수 있다.
url을 통해 다음과 같이 JSON포맷의 데이터를 제공한다.
import 'dart:convert';
import 'package:http/http.dart' as http;
const List<String> currenciesList = [
'AUD',
'BRL',
'CAD',
'CNY',
'EUR',
'GBP',
'HKD',
'IDR',
'ILS',
'INR',
'JPY',
'MXN',
'NOK',
'NZD',
'PLN',
'RON',
'RUB',
'SEK',
'SGD',
'USD',
'ZAR'
];
const List<String> cryptoList = ['BTC', 'ETH', 'LTC'];
const coinAPIURL = 'https://rest.coinapi.io/v1/exchangerate';
const apiKey = 'AD5391A8-A59A-4219-B0E9-1C6FDDB8CB28';
class CoinData {
Future getCoinData(String selectedCurrency) async {
Map<String, String> cryptoPrices = {};
for (String crypto in cryptoList) {
String requestURL =
'$coinAPIURL/$crypto/$selectedCurrency?apikey=$apiKey';
http.Response response = await http.get(Uri.parse(requestURL));
if (response.statusCode == 200) {
var decodedData = jsonDecode(response.body);
double lastPrice = decodedData['rate'];
cryptoPrices[crypto] = lastPrice.toStringAsFixed(0);
} else {
print(response.statusCode);
throw 'Problem with the get request';
}
}
return cryptoPrices;
}
}
※반환하는 cryptoPrices는 다음과 같다.※
{'BTC' : 'BTC에 대한 selectedCurrency 환율',
'ETH' : 'ETH에 대한 selectedCurrency 환율',
'LTC' : 'LTC에 대한 selectedCurrency 환율' }
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'coin_data.dart';
import 'dart:io' show Platform;
class PriceScreen extends StatefulWidget {
_PriceScreenState createState() => _PriceScreenState();
}
class _PriceScreenState extends State<PriceScreen> {
String selectedCurrency = 'AUD';
DropdownButton<String> androidDropdown() {
List<DropdownMenuItem<String>> dropdownItems = [];
for (String currency in currenciesList) {
var newItem = DropdownMenuItem(
child: Text(currency),
value: currency,
);
dropdownItems.add(newItem);
}
return DropdownButton<String>(
value: selectedCurrency,
items: dropdownItems,
onChanged: (value) {
setState(() {
selectedCurrency = value;
getData();
});
},
);
}
CupertinoPicker iOSPicker() {
List<Text> pickerItems = [];
for (String currency in currenciesList) {
pickerItems.add(Text(currency));
}
return CupertinoPicker(
backgroundColor: Colors.lightBlue,
itemExtent: 32.0,
onSelectedItemChanged: (selectedIndex) {
setState(() {
selectedCurrency = currenciesList[selectedIndex];
getData();
});
},
children: pickerItems,
);
}
Map<String, String> coinValues = {};
bool isWaiting = false;
void getData() async {
isWaiting = true;
try {
var data = await CoinData().getCoinData(selectedCurrency);
isWaiting = false;
setState(() {
coinValues = data;
});
} catch (e) {
print(e);
}
}
void initState() {
super.initState();
getData();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('🤑 Coin Ticker'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
CryptoCard(
cryptoCurrency: 'BTC',
value: isWaiting ? '?' : coinValues['BTC'],
selectedCurrency: selectedCurrency,
),
CryptoCard(
cryptoCurrency: 'ETH',
value: isWaiting ? '?' : coinValues['ETH'],
selectedCurrency: selectedCurrency,
),
CryptoCard(
cryptoCurrency: 'LTC',
value: isWaiting ? '?' : coinValues['LTC'],
selectedCurrency: selectedCurrency,
),
],
),
Container(
height: 150.0,
alignment: Alignment.center,
padding: EdgeInsets.only(bottom: 30.0),
color: Colors.lightBlue,
child: Platform.isIOS ? iOSPicker() : androidDropdown(),
),
],
),
);
}
}
class CryptoCard extends StatelessWidget {
const CryptoCard({
this.value,
this.selectedCurrency,
this.cryptoCurrency,
});
final String value;
final String selectedCurrency;
final String cryptoCurrency;
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 0),
child: Card(
color: Colors.lightBlueAccent,
elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 28.0),
child: Text(
'1 $cryptoCurrency = $value $selectedCurrency',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
),
),
),
),
);
}
}
하단의 메뉴에서 원하는 화폐종류를 선택하면 그에 대한 가상화폐의 환율을 제공한다.