flutterdartvisual-studio-codecoinmarketcap

Using http.dart to Call CoinMarketCap API. Not sure what to do


So I'm new to flutter and dart and am trying to call from the CoinMarketCap API. I'm using the HTTP package to call the data and the API. I'm not super familiar with them but here's what I came up with...

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

Future<Payload> getCryptoPrices() async {
    var response = await http.get(Uri.parse(
        "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD"),

        headers: {
          'X-CMC_PRO_API_KEY': 'my-key',
          "Accept": "application/json",
        });

    if (response.statusCode == 200) {
      Payload payload = payloadFromJson(data.body);
      return payload;      
    }
  }

I get a couple of errors:

The name 'Payload' isn't a type so it can't be used as a type argument

The function 'payloadFromJson' isn't defined

Undefined name 'data'

Am I not successfully importing JSON? I'm not sure how to fix the error. What do I need to do to successfully make a API Call? Any feedback would be great.


Solution

  • CODE UPDATED #1

    import 'package:wnetworking/wnetworking.dart';
    
    
    class CoinMarketCap {
      static const _apiKey = '111111111111111111111111111111';
      static const _url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency';
    
      static Future<void> getListingLatest(int limit) async {
        var url = '$_url/listings/latest?start=1&limit=$limit&convert=USD';
        var result = await HttpReqService.get<JMap>(
          url, 
          auth: AuthType.apiKey,
          authData: MapEntry('X-CMC_PRO_API_KEY', _apiKey)
        );
        var coins = (result?['data'] as List).cast<JMap>().map<String>((e) => e['name']);
        print(coins);
      }
    }
    
    void main(List<String> args) async {
      await CoinMarketCap.getListingLatest(7);
      print('\nJob done!');
    }
    

    Output:

    (Bitcoin, Ethereum, Tether, USD Coin, BNB, XRP, Cardano)
    
    Job done!