Flutter加密货币数据获取插件coingecko_dart的使用

Flutter加密货币数据获取插件coingecko_dart的使用

coingecko_dart

A Dart/Flutter Wrapper for the CoinGecko API (V3).

GET STARTED

ADD DEPENDENCY

dependencies:
  coingecko_dart: ^0.1.0

EASY TO USE

To get started with the api, all you have to do is initialize it like so and call the method of your choice!

CoinGeckoApi apiInstance = CoinGeckoApi();
//Future<CoinGeckoResult> result = await apiInstance.callMethod();

METHODS AVAILABLE

GENERAL

ping()                      -> /ping

Example

Future<CoinGeckoResult<bool>> pingResponse = await apiInstance.ping();
bool requestIsSuccessful = pingResponse.data;

SIMPLE

- simplePrice()                 -> /simple/price
- simpleTokenPrice()            -> /simple/token_price/{id}
- simpleSupportedVsCurrencies() -> /simple/supported_vs_currencies

RETURN TYPES

respectively matching the above methods

  • CoinGeckoResult<List<PricedCoin>>
  • CoinGeckoResult<List<SimpleToken>>
  • CoinGeckoResult<List<String>>

Example

// Obtain prices and some other data of "iota" coin in "jpy" and "usd"
CoinGeckoResult<List<PricedCoin>> result = await apiInstance.simplePrice(
  ids: ["iota"],
  vs_currencies: ["usd", "jpy"],
  includeLastUpdatedAt: true,
  includeMarketCap: true,
);

You can use var to store the result if you’re not too sure about the return data type.

// Obtain price and some other data of ethereum token "AAVE" in 'inr','usd' and 'eth'
var result = await apiInstance.simpleTokenPrice(
  id: 'ethereum',
  contractAddresses: ['0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9'],
  vs_currencies: ['inr', 'usd', 'eth'],
);

// List of currencies against crypto ex: ['usd','inr','jpy','cad']
var result = await apiInstance.simpleSupportedVsCurrencies();

COINS

1. listCoins()                   -> /coins/list
2. getCoinMarkets()              -> /coins/markets
3. getCoinData()                 -> /coins/{id}
4. getCoinTickers()              -> /coins/{id}/tickers
5. getCoinHistory()              -> /coins/{id}/history
6. getCoinMarketChart()          -> /coins/{id}/market_chart
7. getCoinMarketChartRanged()    -> /coins/{id}/market_chart/range

RETURN TYPES

respectively matching the above methods

  • CoinGeckoResult<List<Coin>>
  • CoinGeckoResult<List<FullCoin>>
  • ** CoinGeckoResult<Coin>**
  • CoinGeckoResult<List<CoinTicker>>
  • ** CoinGeckoResult<Coin>**
  • CoinGeckoResult<List<CoinDataPoint>>
  • CoinGeckoResult<List<CoinDataPoint>>

** (3,5) Note: Data class is not fully implemented, use (coin.json[]) property instead to access the object directly.

Example

// Obtain a list of Coin() objects
var result = await apiInstance.listCoins(includePlatformFlag: false);
print(result.data.any((element) => element.symbol.toUpperCase() == "BTC")); // true

// Obtain a list of FullCoin() objects
var result = await apiInstance.getCoinMarkets(
  vsCurrency: 'usd',
  coinIds: ['bitcoin', 'iota', 'tether'],
  category: CoinCategories.STABLECOIN,
  sparkline: true,
  priceChangePercentage: [MarketInterval.T_1H, MarketInterval.T_24H],
);
if (!result.isError) {
  print(result.data.id[0] == "tether"); // true
} else {
  print("${result.errorCode}, ${result.errorMessage}");
}

// Obtain all data of crypto with id 'bitcoin' with localization and sparkline 7 days data
var result = await apiInstance.getCoinData(
  id: 'bitcoin',
  localization: true,
  sparkline: true,
);
print(result.data.json['block_time_in_minutes'] == 10); // true

// Obtain tickers of crypto 'bitcoin'
var result = await apiInstance.getCoinTickers(
  id: "bitcoin",
  includeExchangeLogo: true,
);
// result.data is a list that contains instances of `CoinTicker`

// Obtain full data of bitcoin on 2nd April 2019
var result = await apiInstance.getCoinHistory(
  id: 'bitcoin',
  date: DateTime(2019, 4, 2),
);
print(result.data.json['market_data']['current_price']['usd'] == 4146.321927706636); // true

// A list of CoinDataPoint instances from 30 days back until now, one data point a day
var result = await apiInstance.getCoinMarketChart(
  id: "bitcoin",
  vsCurrency: "usd",
  days: 30,
  interval: ChartTimeInterval.DAILY,
);

// A list of CoinDataPoint instances between from Date and to Date
var result = await apiInstance.getCoinMarketChartRanged(
  id: "bitcoin",
  vsCurrency: "usd",
  from: DateTime(2021, 4, 2),
  to: DateTime(2021, 4, 10),
);

CONTRACT

getContractTokenData()        -> /coins/{id}/contract/{contract_address}
getContractMarketChart()      -> /coins/{id}/contract/{contract_address}/market_chart
getContractMarketChartRanged() -> /coins/{id}/contract/{contract_address}/market_chart/range

EXCHANGES

getExchanges()                -> /exchanges
getExchangeRatesBtc()         -> /exchange_rates

TRENDING

getSearchTrending()           -> /search/trending

GLOBAL

getGlobalCoins()              -> /global
getGlobalDefi()               -> /global/decentralized_finance_defi

更多关于Flutter加密货币数据获取插件coingecko_dart的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter加密货币数据获取插件coingecko_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用coingecko_dart插件来获取加密货币数据的Flutter代码示例。这个插件允许你访问CoinGecko API,从而获取各种加密货币的数据。

首先,确保在你的pubspec.yaml文件中添加coingecko_dart依赖:

dependencies:
  flutter:
    sdk: flutter
  coingecko_dart: ^最新版本号  # 请替换为最新的版本号

然后运行flutter pub get来安装依赖。

接下来,我们编写一个简单的Flutter应用来展示如何使用这个插件。

import 'package:flutter/material.dart';
import 'package:coingecko_dart/coingecko_dart.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late CoinGeckoClient _coinGeckoClient;
  late Future<Map<String, dynamic>> _coinDataFuture;

  @override
  void initState() {
    super.initState();
    _coinGeckoClient = CoinGeckoClient();
    _coinDataFuture = _fetchCoinData('bitcoin'); // 例如获取比特币数据
  }

  Future<Map<String, dynamic>> _fetchCoinData(String coinId) async {
    try {
      final response = await _coinGeckoClient.getCoins(coinIds: [coinId]);
      return response?.data?[0]; // 返回第一个匹配的结果
    } catch (e) {
      print('Error fetching coin data: $e');
      return {};
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'CoinGecko Data Fetcher',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('CoinGecko Data Fetcher'),
        ),
        body: Center(
          child: FutureBuilder<Map<String, dynamic>>(
            future: _coinDataFuture,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else if (snapshot.data?.isEmpty ?? true) {
                  return Text('No data found');
                } else {
                  final coinData = snapshot.data!;
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('Name: ${coinData['name']}'),
                      Text('Symbol: ${coinData['symbol']}'),
                      Text('Market Cap: ${coinData['market_cap']['usd']} USD'),
                      Text('Price: ${coinData['current_price']['usd']} USD'),
                    ],
                  );
                }
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们做了以下几件事:

  1. 创建并初始化CoinGeckoClient实例:这个实例将用于与CoinGecko API进行通信。
  2. 定义_fetchCoinData方法:该方法使用_coinGeckoClient来获取指定加密货币的数据。在这个例子中,我们获取的是比特币的数据。
  3. 使用FutureBuilder来显示数据FutureBuilder允许我们根据异步操作(在这个例子中是获取加密货币数据)的状态来构建UI。如果操作完成并且没有错误,它将显示获取到的数据;否则,它将显示一个加载指示器或错误信息。

运行这个应用,你应该能够看到比特币的一些基本信息,如名称、符号、市值和当前价格。

请注意,这个示例仅展示了如何获取单个加密货币的数据。coingecko_dart插件还支持许多其他功能,如获取市场趋势、交易对信息等,你可以查阅其官方文档以获取更多信息。

回到顶部