【问题标题】:Flutter use for loop to fetch data from apiFlutter 使用 for 循环从 api 中获取数据
【发布时间】:2020-09-01 04:46:29
【问题描述】:

我正在学习颤振,并在我的项目中尝试使用 coinapi https://www.coinapi.io/ 以美元计算加密货币的汇率。

数据格式:

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

当我通过在 requestURL 中手动指定加密货币 BTC 来运行代码时,代码会获取数据:

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

但是,当使用项目索引(即 cryptoList[i])分配加密货币值时,在 for 循环中代码无法运行。我得到状态码 550,get 请求有问题

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

以下是获取每种加密货币汇率的代码。


  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';
      }
    }
  }
}

如何修复上述代码以使用 for 循环从 coinapi 获取数据?最终我喜欢将数据添加到地图 Map cryptoPrices = {};

输出要求为

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

【问题讨论】:

  • 你能分享一下你收到的json的结构吗?
  • jsondecode数据为:{time: 2020-09-01T04:54:33.1460000Z,asset_id_base: BTC,asset_id_quote: AUD, rate: 15946.065655013266}

标签: flutter


【解决方案1】:

请改成

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

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

测试代码输出

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

测试代码

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),
      ),
    );
  }
}

解析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,
    };
}

完整代码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),
      ),
    );
  }
}

【讨论】:

  • 酷。多数民众赞成在工作。您能否建议如何将值添加到 MAP Map cryptoPrices = {};
  • 请使用payloadFromJson(jsonString),见update parse json,然后可以使用payload.rate
  • 有效载荷有效载荷 = payloadFromJson(response.body);双倍价格 = payload.rate;
  • 基本上希望输出为:{BTC: 15972, ETH: 607, LTC: 84}
  • 查看完整代码2,使用地图。使用 dataMap[cryptoList[i]] = yourNo;和字符串 a = currencyToJson(dataMap);
【解决方案2】:

在@chunhunghan 的帮助下,以下代码允许获取加密货币(BTC、ETH、LTC)的数据并更新 cryptoList 映射

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;
  }
}

【讨论】:

    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 2019-10-31
    • 2016-10-11
    • 1970-01-01
    相关资源
    最近更新 更多