Get a collection of stock statistics and quotes using Flutter and the IEX JSON API

IEX JSON API Integration:

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

   Future<Map<String,dynamic>> getStocksData() async {
 
  const url = 'https://cloud.iexapis.com/stable/stock/market/batch?symbols=aapl,fb&types=quote&token=Hidden';
   final response = await http.get(url);
   final decodedResponse = json.decode(response.body).keys();
   final data = Stocks.fromJson(decodedResponse);
     
     return jsonDecode(response.body).keys();
  
   }

{"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.","...

Development 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 ...

Custom Class Definition:

import 'dart:convert';

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

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

class Stocks {
  String symbol;
  // Include other attributes similar to the existing ones

  Stocks({
    this.symbol,
    // Add more attribute definitions here
  });

  factory Stocks.fromJson(Map<String, dynamic> json) => Stocks(
    symbol: json["symbol"],
    // Define mappings for additional attributes
  );

  Map<String, dynamic> toJson() => {
    "symbol": symbol,
    // Include mappings for new attributes
  };
}

No errors encountered during execution. https://i.sstatic.net/fwBl0.png

Your feedback and support are highly appreciated!

Answer №1

Seems like the issue lies in `.expand((data) => (data as List))`. It appears that your API is returning a JSON Object (Map) instead of a JSON Array (List).

Another observation is that "AAPL" serves as a key in the JSON Object, with its corresponding value being another JSON Object. If you want to map these values to your Class, you can utilize the expand method to extract the value of "AAPL" and pass it to your factory method fromJSON.

It's crucial to ensure that the keys you are attempting to map to your Class actually exist in the passed JSON Object. To handle dynamically appearing keys, consider using the Null-aware Operator.

Null-aware operators in Dart allow for conditional computations based on whether a value is null or not, providing shorthand for longer expressions.

To simplify things, you may want to reconsider using Streams and opt for refactoring your code to be more asynchronous by relying solely on Future.

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

Lastly, I highly recommend checking out:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for setting default parameters using a recompose, lifecycle HOC?

I've created a custom recompose, lifecycle HOC: import { lifecycle } from 'recompose'; export function myHoc(title) { return lifecycle({ componentDidMount() { console.log(title) } }); } export default my ...

Choose a particular character in a text that corresponds with a regular expression in Javascript

I am looking to replace the symbols < and > within the text. I have constructed a regular expression as follows: (<span[^>]+class\s*=\s*("|')subValue\2[^>]*>)[^<]*(<\/span>)|(<br(\/*)>) This ...

Determine whether the keyCode value matches any items within a specific array

Currently, as I am in the process of creating a small typewriter application, I have encountered an issue with determining if the button pressed matches the value of specific span elements. To provide further context, there are two divs each containing sp ...

How to Pass Values in handleChange Event in Typescript

I have noticed that most online examples of handling change events only pass in the event parameter, making the value accessible automatically. However, I encountered an error stating that the value is not found when trying to use it in my handleChange fun ...

What is the reason for the React component being rendered four times?

My React component is fetching data from Firestore and storing it in the items array. However, I am encountering an issue where the menus variable contains three empty arrays that are being rendered on the page. Initially, I used an async function to fetc ...

Axios - retrieving merchandise

I have created an endpoint that retrieves all product information in JSON format. I am attempting to display this data on my index.html page using Axios, but I am encountering difficulties with getting the data correctly. This is my first time working with ...

Div Randomly Transforms Its Vertical Position

After successfully creating a VS Code Extension for code completion, I decided to develop a website as a landing page where users can sign up and customize their extension settings. The editor I built pops up first on the page seemed to be working fine in ...

Some models showcase crisp textures with Thee.js, while others appear hazy (especially custom designs)

As a beginner in the realm of Three.js, I have been following a tutorial on texturing custom geometric shapes. The tutorial used a classic head OBJ file as a test case, which worked perfectly fine. However, when I tried to tweak the script to render my own ...

The height of the div element is automatically adjusted to zero

I am dealing with a simple layout where I have a main div that floats to the left. Within this main div, I nest other divs using the clear both style. Below is a simplified version of my setup: <div id="wrapper" class="floatLeft"> <div id="ma ...

Tips for implementing fluid transitions between mouse X and Y coordinates using JavaScript

I recently developed a function that enables a DOM element to follow the mouse cursor. You can check out the code here. Currently, I am looking for suggestions on how to add a nice animation to this feature. Ideally, I want to incorporate a slight delay w ...

Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this: arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. However, I need to add a condition to the array. If ...

Using the functionalities of the parent component

Exploring Base.vue <template><div>{{ name }}</div></template> <script> export default { data() { return {name: 'Example Component'}; } }; </script> And introducing Extended.vue: <script> ...

Encountering TypeScript error TS2339 while trying to utilize a method from a different class within an event handler and binding the current

My development setup includes a service called DomService for all DOM manipulation tasks. Additionally, I have another service called ModalService that handles modal functionality. Within the ModalService, there are some events being bound, with a method ...

Getting the WatchPosition update just one time

I have implemented this code to continuously retrieve the first position and I need it to keep doing so. var init = function() { navigator.geolocation.getCurrentPosition(function(position) { new_position = position; }, onEr ...

What is the process for incorporating a full-page blog into a blog preview?

I customized a template, but there is a blog section within the div that I am struggling to replicate. Here is the test website for reference: Below is the HTML code for the blog section: <!-- Blog Start --> <section class="section bg ...

Switch Object to WebElement or SearchContext in JavaScript

Looking for the best way to convert an Object to WebElement or SearchContext using JavaScript? In Java, casting as `(WebElement)` or `(SearchContext)` works fine. However, attempting the same in JavaScript with `as Webelement` or `as SearchContext` result ...

The Delay in Meteor's Data Transfer between Publish and Subscription

I am utilizing d3 to visualize a compilation of meteors (Hostiles) on an image based on their x and y coordinates. This process is successful for me. However, I have a publish function that verifies the user's login status to determine if they are an ...

Rebooting checkbox data with AJAX on MVC 5 form submission

Within my application, I am utilizing an AJAX BeginForm: @using (Ajax.BeginForm("DeletePages", "Home", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccessDelete", OnFailure = "OnFailureDelete" }, new { id = "ToolBarActionsForm" })) { @Html.A ...

Using jQuery to create sliding animations with left and right transitions

I recently learned about the slideUp and slideDown functions in jQuery. Are there any similar functions or methods for sliding elements to the left or right? ...

Obtain the selected row's ID by leveraging angular.js with either ngSelect or ngOptions

I'm currently working on an angular.js project where I have a dynamic table displaying study results. I want to enhance this by allowing users to view more detailed data about each specific study when they click on the corresponding row in the table. ...