Flutter:从IEX JSON API检索股票统计和报价列表

问题描述 投票:0回答:1

IEX JSON API:

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



   Future<Map<String,dynamic>> getStocks() async {

  // final String url = 
'https://cloud.iexapis.com/stable/stock/market/batch? 
  symbols=aapl,fb&types=quote&token=Hidden';
 //  final client = new http.Client();
  // final streamedRest = await client.send(
  //  http.Request('get', Uri.parse(url))


   const url = 'https://cloud.iexapis.com/stable/stock/market/batch?s 
  ymbols=aapl,fb&types=quote&token=Hidden';
   final response = await http.get(url);
  final decodedResponse = json.decode(response.body).keys();
   final data = Stocks.fromJson(decodedResponse);

    //http.Response response = await http.get(Uri, headers: {"Accept": 
   "application/json"});
   //print(jsonDecode(response.body).keys());
     return jsonDecode(response.body).keys();
    //  return streamedRest.stream
   //   .transform(utf8.decoder)
    // .transform(json.decoder)
    // .expand((data) => (data as List<dynamic>))
   //  .map((data) => Stocks.fromJSON(data));
   }

{“ AAPL”:{“ stats”:{“ week52change”:0.108189,“ week52high”:244.8,“ week52low”:142,“ marketcap”:1100781864400,“员工”:132000,“ day200MovingAvg”:196.46,“ day50MovingAvg“:220.62,” float“:4512324403.94,” avg10Volume“:23328121.8,” avg30Volume“:26924247.43,” ttmEPS“:11.8267,” ttmDividendRate“:2.96,” companyName“:” Apple,Inc。“,” sharesOutstanding“: 4519180000,“ maxChangePercent”:240.1683,“ year5ChangePercent”:1.315,“ year2ChangePercent”:0.5505,“ year1ChangePercent”:0.108189,“ ytdChangePercent”:0.542427,“ month6ChangePercent”:0.186574,“ month3ChangePercent”:0.176601,“ month1ChangePercent”:0.1020 “ day30ChangePercent”:0.113509,“ day5ChangePercent”:0.030329,“ nextDividendDate”:null,“ dividendYield”:0.012152065029969619,“ nextEarningsDate”:“ 2019-10-30”,“ exDividendDate”:“ 2019-08-09”,“ peRatio “:20.75,” beta“:1.534551916699308},” quote“:{” symbol“:” AAPL“,” companyName“:” Apple,Inc。“,” primaryExchange“:” NASDAQ“,” calculationPrice“:” tops“ ,“ open”:null,“ openTime”:null,“ close”:null,“ closeTime”:null,“ high”:null,“ low”:null,“ latestPri ce“:245.395,” latestSource“:” IEX实时价格“,” latestTime“:” 12:37:57

日志:

在调试模式下为x86构建的Android SDK上启动lib \ main.dart ...正在初始化gradle ...解决依赖性...正在运行Gradle任务'assembleDebug'...构建build \ app \ outputs \ apk \ debug \ app-debug.apk。I / OpenGLRenderer(4854):初始化的EGL,版本1.4D / OpenGLRenderer(4854):交换行为1D /(4854):HostConnection :: get()建立新的主机连接0xdc20bf00,tid 4881D / EGL_emulation(4854):eglCreateContext:0xe3d47760:maj 2 min 0 rcv 2D / EGL_emulation(4854):eglMakeCurrent:0xe3d47760:ver 2 0(tinfo 0xc6b24a30)D /(4854):HostConnection :: get()建立新的主机连接0xc6b386c0,TID 4874D / EGL_emulation(4854):eglCreateContext:0xdc27d780:maj 2 min 0 rcv 2D / EGL_emulation(4854):eglMakeCurrent:0xdc27d780:ver 2 0(tinfo 0xc6b24dc0)正在将文件同步到针对x86构建的设备Android SDK ...I / Choreographer(4854):跳过279帧!该应用程序可能在其主线程上做太多工作。D / EGL_emulation(4854):eglMakeCurrent:0xe3d47760:ver 2 0(tinfo 0xc6b24a30)I / OpenGLRenderer(4854):戴维!持续时间= 6180ms;标志= 1,IntendedVsync = 596431275408,Vsync = 601081275222,OldestInputEvent = 9223372036854775807,NewestInputEvent = 0,HandleInputStart = 601083214976,AnimationStart = 601083253387,PerformTraversalsStart = 601083255696,DrawStart = 601096302305,SyncQueued = 601333900000s,StartStart = Draw335、694535335418,SyncStart = Draw335 602308827762,FrameCompleted = 602612881859,DequeueBufferDuration = 66828000,QueueBufferDuration = 276000,D / EGL_emulation(4854):eglMakeCurrent:0xdc27d780:ver 2 0(tinfo 0xc6b24dc0)

班级

import 'dart:convert';

Stocks stocksFromJson(String str) => Stocks.fromJson(json.decode(str));

String stocksToJson(Stocks data) => json.encode(data.toJson());

class Stocks {
  String symbol;
  String companyName;
  String primaryExchange;
  String calculationPrice;
  int open;
  int openTime;
  double close;
  int closeTime;
  double high;
  double low;
  double latestPrice;
  String latestSource;
  String latestTime;
  int latestUpdate;
  int latestVolume;
  dynamic iexRealtimePrice;
  dynamic iexRealtimeSize;
  dynamic iexLastUpdated;
  double delayedPrice;
  int delayedPriceTime;
  double extendedPrice;
  double extendedChange;
  double extendedChangePercent;
  int extendedPriceTime;
  double previousClose;
  int previousVolume;
  int change;
  double changePercent;
  int volume;
  dynamic iexMarketPercent;
  dynamic iexVolume;
  int avgTotalVolume;
  dynamic iexBidPrice;
  dynamic iexBidSize;
  dynamic iexAskPrice;
  dynamic iexAskSize;
  int marketCap;
  double peRatio;
  double week52High;
  int week52Low;
  double ytdChange;
  int lastTradeTime;
  bool isUsMarketOpen;

  Stocks({
    this.symbol,
    this.companyName,
    this.primaryExchange,
    this.calculationPrice,
    this.open,
    this.openTime,
    this.close,
    this.closeTime,
    this.high,
    this.low,
    this.latestPrice,
    this.latestSource,
    this.latestTime,
    this.latestUpdate,
    this.latestVolume,
    this.iexRealtimePrice,
    this.iexRealtimeSize,
    this.iexLastUpdated,
    this.delayedPrice,
    this.delayedPriceTime,
    this.extendedPrice,
    this.extendedChange,
    this.extendedChangePercent,
    this.extendedPriceTime,
    this.previousClose,
    this.previousVolume,
    this.change,
    this.changePercent,
    this.volume,
    this.iexMarketPercent,
    this.iexVolume,
    this.avgTotalVolume,
    this.iexBidPrice,
    this.iexBidSize,
    this.iexAskPrice,
    this.iexAskSize,
    this.marketCap,
    this.peRatio,
    this.week52High,
    this.week52Low,
    this.ytdChange,
    this.lastTradeTime,
    this.isUsMarketOpen,
  });

  factory Stocks.fromJson(Map<String, dynamic> json) => Stocks(
    symbol: json["symbol"],
    companyName: json["companyName"],
    primaryExchange: json["primaryExchange"],
    calculationPrice: json["calculationPrice"],
    open: json["open"],
    openTime: json["openTime"],
    close: json["close"].toDouble(),
    closeTime: json["closeTime"],
    high: json["high"].toDouble(),
    low: json["low"].toDouble(),
    latestPrice: json["latestPrice"].toDouble(),
    latestSource: json["latestSource"],
    latestTime: json["latestTime"],
    latestUpdate: json["latestUpdate"],
    latestVolume: json["latestVolume"],
    iexRealtimePrice: json["iexRealtimePrice"],
    iexRealtimeSize: json["iexRealtimeSize"],
    iexLastUpdated: json["iexLastUpdated"],
    delayedPrice: json["delayedPrice"].toDouble(),
    delayedPriceTime: json["delayedPriceTime"],
    extendedPrice: json["extendedPrice"].toDouble(),
    extendedChange: json["extendedChange"].toDouble(),
    extendedChangePercent: json["extendedChangePercent"].toDouble(),
    extendedPriceTime: json["extendedPriceTime"],
    previousClose: json["previousClose"].toDouble(),
    previousVolume: json["previousVolume"],
    change: json["change"],
    changePercent: json["changePercent"].toDouble(),
    volume: json["volume"],
    iexMarketPercent: json["iexMarketPercent"],
    iexVolume: json["iexVolume"],
    avgTotalVolume: json["avgTotalVolume"],
    iexBidPrice: json["iexBidPrice"],
    iexBidSize: json["iexBidSize"],
    iexAskPrice: json["iexAskPrice"],
    iexAskSize: json["iexAskSize"],
    marketCap: json["marketCap"],
    peRatio: json["peRatio"].toDouble(),
    week52High: json["week52High"].toDouble(),
    week52Low: json["week52Low"],
    ytdChange: json["ytdChange"].toDouble(),
    lastTradeTime: json["lastTradeTime"],
    isUsMarketOpen: json["isUSMarketOpen"],
  );

  Map<String, dynamic> toJson() => {
    "symbol": symbol,
    "companyName": companyName,
    "primaryExchange": primaryExchange,
    "calculationPrice": calculationPrice,
    "open": open,
    "openTime": openTime,
    "close": close,
    "closeTime": closeTime,
    "high": high,
    "low": low,
    "latestPrice": latestPrice,
    "latestSource": latestSource,
    "latestTime": latestTime,
    "latestUpdate": latestUpdate,
    "latestVolume": latestVolume,
    "iexRealtimePrice": iexRealtimePrice,
    "iexRealtimeSize": iexRealtimeSize,
    "iexLastUpdated": iexLastUpdated,
    "delayedPrice": delayedPrice,
    "delayedPriceTime": delayedPriceTime,
    "extendedPrice": extendedPrice,
    "extendedChange": extendedChange,
    "extendedChangePercent": extendedChangePercent,
    "extendedPriceTime": extendedPriceTime,
    "previousClose": previousClose,
    "previousVolume": previousVolume,
    "change": change,
    "changePercent": changePercent,
    "volume": volume,
    "iexMarketPercent": iexMarketPercent,
    "iexVolume": iexVolume,
    "avgTotalVolume": avgTotalVolume,
    "iexBidPrice": iexBidPrice,
    "iexBidSize": iexBidSize,
    "iexAskPrice": iexAskPrice,
    "iexAskSize": iexAskSize,
    "marketCap": marketCap,
    "peRatio": peRatio,
    "week52High": week52High,
    "week52Low": week52Low,
    "ytdChange": ytdChange,
    "lastTradeTime": lastTradeTime,
    "isUSMarketOpen": isUsMarketOpen,
  };
}

谢谢您的帮助!

javascript flutter dart stock algorithmic-trading
1个回答
1
投票

看起来是.expand((data) => (data as List)),看起来您的API返回了JSON对象(映射),而不是JSON数组(列表)

[我还想出了另一个细节,“ AAPL”是JSON对象上的键,该值是另一个JSON对象,如果要将其值映射到Class,则可以使用扩展获取值“ AAPL”,并将其传递给您的工厂fromJSON

[其他重要的事情是要确保您尝试映射到Class的密钥在传递的JSON对象中存在。为了避免动态键(可能不会出现的键)出现问题,您可以使用Null-aware运算符

dart中的可识别空值的运算符使您可以根据值是否为空来进行计算。它是较长表达式的简写。

[使事情变得简单一些的建议,也许是不使用Streams,您可以仅使用Future重构代码以实现异步内容

const url = 'http://example.com/';
final response = await http.get(url);
final decodedResponse = json.decode(response);
final yourObject = Class.fromJSON(decodedResponse);

最后但并非最不重要的一点,我强烈建议您看一下:

© www.soinside.com 2019 - 2024. All rights reserved.