简体   繁体   English

Flutter 使用for循环从api中取数据

[英]Flutter use for loop to fetch data from api

I'm learning flutter and in my project trying to get rate of a cryptocurrency in USD using coinapi https://www.coinapi.io/ .我正在学习 flutter 并且在我的项目中尝试使用 coinapi https://www.coinapi.io/获取美元加密货币的汇率。

the data format:数据格式:

{
  "time": "2020-09-01T04:56:23.0070000Z",
  "asset_id_base": "BTC",
  "asset_id_quote": "AUD",
  "rate": 15949.923298625433767473523127
}

When i run the code by manually specifying the cryptocurrency BTC in the requestURL, the code fetches the data:当我通过在 requestURL 中手动指定加密货币 BTC 运行代码时,代码获取数据:

String requestURL ='$coinAPIURL/BTC/$selectedCurrency?apikey=$apiKey';

But when the cryptocurrency value is assigned using the item index ie cryptoList[i], in the for loop the code fails to run.但是,当使用项目索引(即 cryptoList[i])分配加密货币值时,for 循环中的代码无法运行。 I get statuscode 550, problem with the get request我得到状态码 550,get 请求有问题

String requestURL = '$coinAPIURL/$cryptoList[i]/$selectedCurrency?apikey=$apiKey';

Below is the code to get the rate for each cryptocurrency.以下是获取每种加密货币汇率的代码。


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

const coinAPIURL = 'https://rest.coinapi.io/v1/exchangerate';
const apiKey = 'apikey from cointapi';

List allRates = [];

class CoinData {
  Future getCoinData(String selectedCurrency) async {
 
    //for (String crypto in cryptoList) {
    for (int i=0; i < cryptoList.length; i++) {
      print(cryptoList[i]);
      String requestURL =
          '$coinAPIURL/BTC/$selectedCurrency?apikey=$apiKey';
      http.Response response = await http.get(requestURL);
      if (response.statusCode == 200) {
        var decodedData = jsonDecode(response.body);
        double price = decodedData['rate'];
        //cryptoPrices[crypto] = price.toStringAsFixed(0);
        print(decodedData);
      } else {
        print(response.statusCode);
        throw 'Problem with the get request';
      }
    }
  }
}

How do i fix the above code to fetch the data from the coinapi using a for loop?我如何修复上面的代码以使用 for 循环从 coinapi 获取数据? Eventually I like to add the data to a map Map<String, String> cryptoPrices = {};最终我想将数据添加到 map Map<String, String> cryptoPrices = {};

Output required as Output 需要作为

{BTC: 15972, ETH: 607, LTC: 84}

Please change to请改为

String requestURL = '$coinAPIURL/${cryptoList[i]}/$selectedCurrency?apikey=$apiKey';
  

use {$cryptoList[i]} not $cryptoList[i]使用{$cryptoList[i]}而不是$cryptoList[i]

output of test code测试码output

I/flutter ( 4733): BTC
I/flutter ( 4733): https://rest.coinapi.io/v1/exchangerate/BTC/?apikey=apikey from cointapi
I/flutter ( 4733): ETH
I/flutter ( 4733): https://rest.coinapi.io/v1/exchangerate/ETH/?apikey=apikey from cointapi
I/flutter ( 4733): LTC
I/flutter ( 4733): https://rest.coinapi.io/v1/exchangerate/LTC/?apikey=apikey from cointapi

test code测试代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(       
        primarySwatch: Colors.blue,       
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<String> cryptoList = [
    'BTC',
    'ETH',
    'LTC',
  ];
  String coinAPIURL = 'https://rest.coinapi.io/v1/exchangerate';
  String apiKey = 'apikey from cointapi';
  String selectedCurrency = "";
  void _incrementCounter() {
    for (int i=0; i < cryptoList.length; i++) {
      print(cryptoList[i]);
      String requestURL = '$coinAPIURL/${cryptoList[i]}/$selectedCurrency?apikey=$apiKey';
      print(requestURL);
    }
    setState(() {     
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {    
    return Scaffold(
      appBar: AppBar(       
        title: Text(widget.title),
      ),
      body: Center(        
        child: Column(          
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Parse json解析 json

// To parse this JSON data, do
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
    Payload({
        this.time,
        this.assetIdBase,
        this.assetIdQuote,
        this.rate,
    });

    DateTime time;
    String assetIdBase;
    String assetIdQuote;
    String rate;

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

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

full code 2完整代码 2

import 'dart:convert';

import 'package:flutter/material.dart';

Map<String, int> currencyFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, int>(k, v));

String currencyToJson(Map<String, int> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, v)));

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

class MyApp extends StatelessWidget {  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(       
        primarySwatch: Colors.blue,       
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<String> cryptoList = [
    'BTC',
    'ETH',
    'LTC',
  ];
  String coinAPIURL = 'https://rest.coinapi.io/v1/exchangerate';
  String apiKey = 'apikey from cointapi';
  String selectedCurrency = "";

  Map<String, int> dataMap = {};

  void _incrementCounter() {
    for (int i=0; i < cryptoList.length; i++) {
      print(cryptoList[i]);
      String requestURL = '$coinAPIURL/${cryptoList[i]}/$selectedCurrency?apikey=$apiKey';
      print(requestURL);

      dataMap[cryptoList[i]] = 123;
    }

    String a = currencyToJson(dataMap);
    print(a);

    setState(() {     
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {    
    return Scaffold(
      appBar: AppBar(       
        title: Text(widget.title),
      ),
      body: Center(        
        child: Column(          
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

with help from @chunhunghan, the below code allows to fetch data for cryptocurrencies (BTC, ETH, LTC) and updates the cryptoList map在@chunhunghan 的帮助下,下面的代码允许获取加密货币(BTC、ETH、LTC)的数据并更新 cryptoList map

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

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

const coinAPIURL = 'https://rest.coinapi.io/v1/exchangerate';
const apiKey = 'need to apply for api key from coinapi';

class CoinData {
  Future getCoinData(String selectedCurrency) async {
       
    Map<String, String> cryptoPrices = {};
    
    for (int i = 0; i < cryptoList.length; i++) {
      print(cryptoList[i]);
      String requestURL =
          '$coinAPIURL/${cryptoList[i]}/$selectedCurrency?apikey=$apiKey';
      http.Response response = await http.get(requestURL);

      if (response.statusCode == 200) {
        var decodedData = jsonDecode(response.body);
        double price = decodedData['rate'];
        cryptoPrices[cryptoList[i]] = price.toStringAsFixed(0);
        print(cryptoPrices);
      } else {
        print(response.statusCode);
        throw 'Problem with the get request';
      }
    }
    return cryptoPrices;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM