dart 我需要帮助获取API

ars1skjm  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(153)

我试图从端点获取比特币价格并显示它,但我不知道如何做到这一点。
这是我到目前为止所做的。

class PriceScreen extends StatefulWidget {
  const PriceScreen({super.key});

  @override
  State<PriceScreen> createState() => _PriceScreenState();
}

class _PriceScreenState extends State<PriceScreen> {
  String selectedCurrency = 'USD';

  GetBitcoin? bitcoinData;

 void getData() async {
    try {
      var data = await BitcoinApi().getBitcoin();
      //13. We can't await in a setState(). So you have to separate it out into two steps.
      setState(() {
        bitcoinData = data;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    super.initState();
   getData();
  }

   

  DropdownButton androidDropdown() {
    List<DropdownMenuItem<String>> dropDownPicker = [];
    for (String currency in currenciesList) {
      var newItem = DropdownMenuItem(
        value: currency,
        child: Text(currency),
      );
      dropDownPicker.add(newItem);
    }
    return DropdownButton(
      value: selectedCurrency,
      items: dropDownPicker,
      onChanged: (value) {
        setState(
          () {
            selectedCurrency = value;
            getData();
          },
        );
      },
    );
  }

  CupertinoPicker iOSPicker() {
    List<Text> cupertinoPicker = [];
    for (String currency in currenciesList) {
      cupertinoPicker.add(
        Text(currency),
      );
    }
    return CupertinoPicker(
      itemExtent: 40.0,
      onSelectedItemChanged: (selectedItem) {
        // print(selectedItem);
      },
      children: cupertinoPicker,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('🤑 Coin Ticker'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Padding(
            padding: const 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: const EdgeInsets.symmetric(
                    vertical: 15.0, horizontal: 28.0),
                child: Text(
                  '1 BTC = ${bitcoinData?.rate ?? 'Loading.......'} USD',
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    fontSize: 20.0,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          Container(
            height: 150.0,
            alignment: Alignment.center,
            padding: const EdgeInsets.only(bottom: 30.0),
            color: Colors.lightBlue,
            child: Platform.isIOS ? iOSPicker() : androidDropdown(),
          ),
        ],
      ),
    );
  }
}

这就是模型

import 'dart:convert';

GetBitcoin getBitcoinFromJson(String str) => GetBitcoin.fromJson(json.decode(str));

String getBitcoinToJson(GetBitcoin data) => json.encode(data.toJson());

class GetBitcoin {
    GetBitcoin({
        // required this.time,
        // required this.assetIdBase,
        required this.assetIdQuote,
       required this.rate,
    });

    // DateTime time;
    // String assetIdBase;
    String assetIdQuote;
    double? rate;

    factory GetBitcoin.fromJson(Map<String, dynamic> json) => GetBitcoin(
        // time: DateTime.parse(json["time"]),
        // assetIdBase: json["asset_id_base"],
        assetIdQuote: json["asset_id_quote"],
        rate: json["rate"]?.toDouble(),
    );

    Map<String, dynamic> toJson() => {
        // "time": time.toIso8601String(),
        // "asset_id_base": assetIdBase,
        "asset_id_quote": assetIdQuote,
        "rate": rate,
    };
}

这就是API

import 'package:bitcointicker/model/bitcoin.dart';
import 'package:http/http.dart' as http;

const apiKey = 'D502A312-BB71-48CB-A47B-8E24D7593FFC';

const baseUrl = 'https://rest.coinapi.io/v1/exchangerate/BTC/USD';

class BitcoinApi{

   Future getBitcoin() async {
    var client = http.Client();
    var uri = Uri.parse(baseUrl);
    var response = await client.get(
      uri,
      headers: {
        'X-Api-Key': apiKey,
      },
    );
    if (response.statusCode == 200) {
      var json = response.body;
      return getBitcoinFromJson(json);
    }
  }
}

我是一个小问题,在让API的工作,我试图从一个端点获取比特币的价格,并显示它,但我不知道如何做到这一点。

mqkwyuun

mqkwyuun1#

简单来说,您的问题与Flutter无关,而是与您正在使用的CoinAPI有关。正如他们的文档中所述,API Key的header名称应该是**“X-CoinAPI-Key”**。

相关问题