# Bitcoin Ticker

# 0. Final Product

image-20220203190442932

image-20220203190509796

# 1. services

coin_data.dart

import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

const String apiKey = '########################';
const String endPoint = 'rest.coinapi.io';

const List<String> currenciesList = [
  'CAD',
  'CNY',
  'EUR',
  'GBP',
  'HKD',
  'IDR',
  'JPY',
  'KRW',
  'NZD',
  'USD',
];

const List<String> cryptoList = [
  'BTC',
  'ETH',
  'LTC',
];

class CoinData {
  Future<dynamic> getRate(crypto, currency) async {
    var url = Uri.https(endPoint, '/v1/exchangerate/$crypto/$currency');
    var response = await http.get(url, headers: {"X-CoinAPI-Key": apiKey});
    if (response.statusCode == 200) {
      var jsonResponse = convert.jsonDecode(response.body);
      return jsonResponse;
    } else {
      print(response.statusCode);
    }
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  • 사용할 currencyList와 cryptoList를 작성한다(api 참조)
  • reponse를 받아 jsonResponse로 리턴해준다.

# 2. pages

price_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:bitcoin_ticker/utility/coin_data.dart';
import 'dart:io' show Platform;

class PriceScreen extends StatefulWidget {
  
  _PriceScreenState createState() => _PriceScreenState();
}

class _PriceScreenState extends State<PriceScreen> {
  CoinData coinData = CoinData();
  String selectedCurrency = 'USD';
  Map<String, String> cryptoPrice = {};

  updatePrice() async {
    for (String crypto in cryptoList) {
      var response = await coinData.getRate(crypto, selectedCurrency);
      cryptoPrice[crypto] = response['rate'].toStringAsFixed(0);
    }
    setState(() {});
  }

  List<Widget> cryptoCard() {
    List<Widget> cardList = [];
    for (String crypto in cryptoList) {
      cardList.add(
        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 $crypto = ${cryptoPrice[crypto]} $selectedCurrency',
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 20.0,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      );
    }

    return cardList;
  }

  DropdownButton androidDropdown() {
    return DropdownButton<String>(
      value: selectedCurrency,
      icon: const Icon(Icons.arrow_downward),
      iconSize: 24,
      elevation: 16,
      style: const TextStyle(color: Colors.white),
      underline: Container(
        height: 2,
        color: Colors.white,
      ),
      onChanged: (String newValue) {
        selectedCurrency = newValue;
        updatePrice();
      },
      items: currenciesList.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }

  CupertinoPicker iosPicker() {
    return CupertinoPicker(
      itemExtent: 32,
      onSelectedItemChanged: (value) {
        print(currenciesList[value]);
      },
      children: currenciesList.map((currency) {
        return Text(currency);
      }).toList(),
    );
  }

  
  void initState() {
    // TODO: implement initState
    super.initState();
    updatePrice();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('🤑 Coin Ticker'),
        ),
        body: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Column(
                children: cryptoCard(),
                crossAxisAlignment: CrossAxisAlignment.stretch,
              ),
              Container(
                  height: 150.0,
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(bottom: 30.0),
                  color: Colors.lightBlue,
                  child: Platform.isIOS ? iosPicker() : androidDropdown())
            ]));
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
  • currencyPicker는 사용환경에 따라 ios와 android 버전이 선택이 된다.
    • import 'dart:io' show Platform; 를 통해 사용기기를 확인할 수 있다.
    • Platform.isIOS ? iosPicker() : androidDropdown()
  • for문을 이용하여 cryptoList에 있는 crypto에 관한 시세를 하나하나 불러온다.
  • cryptoPrice라는 map을 정의해주고 값을 저장한다.
  • currenciesList.map을 이용해서 갖고 있는 currency에 대한 버튼을 만들어준다.
  • cardList라는 List 위젯을 리턴해주는 함수를 만들어서 코인에 관한 가격표 리스트를 만든다.