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,"employees":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.102022,"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,"latestPrice":245.395,"latestSource":"IEX real time price","latestTime":"12:37:57

Logs:

Launching lib\main.dart on Android SDK built for x86 in debug mode... Initializing gradle... Resolving dependencies... Running Gradle task 'assembleDebug'... Built build\app\outputs\apk\debug\app-debug.apk. I/OpenGLRenderer( 4854): Initialized EGL, version 1.4 D/OpenGLRenderer( 4854): Swap behavior 1 D/ ( 4854): HostConnection::get() New Host Connection established 0xdc20bf00, tid 4881 D/EGL_emulation( 4854): eglCreateContext: 0xe3d47760: maj 2 min 0 rcv 2 D/EGL_emulation( 4854): eglMakeCurrent: 0xe3d47760: ver 2 0 (tinfo 0xc6b24a30) D/ ( 4854): HostConnection::get() New Host Connection established 0xc6b386c0, tid 4874 D/EGL_emulation( 4854): eglCreateContext: 0xdc27d780: maj 2 min 0 rcv 2 D/EGL_emulation( 4854): eglMakeCurrent: 0xdc27d780: ver 2 0 (tinfo 0xc6b24dc0) Syncing files to device Android SDK built for x86... I/Choreographer( 4854): Skipped 279 frames! The application may be doing too much work on its main thread. D/EGL_emulation( 4854): eglMakeCurrent: 0xe3d47760: ver 2 0 (tinfo 0xc6b24a30) I/OpenGLRenderer( 4854): Davey! duration=6180ms; Flags=1, IntendedVsync=596431275408, Vsync=601081275222, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=601083214976, AnimationStart=601083253387, PerformTraversalsStart=601083255696, DrawStart=601096302305, SyncQueued=601333900000, SyncStart=601335418694, IssueDrawCommandsStart=601335535183, SwapBuffers=602308827762, FrameCompleted=602612881859, DequeueBufferDuration=66828000, QueueBufferDuration=276000, D/EGL_emulation( 4854): eglMakeCurrent: 0xdc27d780: ver 2 0 (tinfo 0xc6b24dc0)

Class

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

No error is generated, but no results either. enter image description here

Thank you in advance for your help!

Dev Ed
  • 831
  • 2
  • 11
  • 23

1 Answers1

1

It looks the problem is .expand((data) => (data as List)), It looks that your API returns a JSON Object (Map) and not JSON Array (List)

Also I figured out another detail, "AAPL" is a key on JSON Object, which the value is another JSON Object, if you want to map its values to your Class you can use the expand to get the value of "AAPL" and pass it to your factory fromJSON

Other important thing, is to be sure that the keys that you are trying to map to your Class exists in JSON Object passed. To avoid problems with dynamically keys (keys that maybe doesn't appear) you can use Null-aware Operator

Null-aware operators in dart allow you to make computations based on whether or not a value is null. It’s shorthand for longer expressions.

An suggestion to make the things a little easy, maybe is don't use Streams for it, you can refactory your code for something async using only Future

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

Last, but not least, I strongly recommend you to give a look on:

  • Hello Helio thank you for your help. was able to fix based on your insights and comments, at the moment I have no error but no results either in the app. Any other ideas? – Dev Ed Oct 31 '19 at 03:44