skip to Main Content

I get this error in my code where I get stocks data from an API and the link changes according to a for loop on a list in the same class. my code is below.

ive tried calling the code like this

        value: jsonDecode(mydata.body)["Time Series (5min)"][0]["1. open"],
        change: jsonDecode(mydata.body)["Time Series (5min)"][0]["5. volume"],

it dosent work. please help
this is the main code.

import 'package:flutter/material.dart';
import '../models/stock_details.dart';
import 'package:http/http.dart';
import 'dart:convert';

class StockList extends StatefulWidget {
  @override
  State<StockList> createState() => _StockListState();
}

class _StockListState extends State<StockList> {
  @override
  void initState() {
    getData();
    super.initState();
  }

  void getData() async {
    int i = 1;
    List<String> initalstocks = ["TCS", "BTC", "IBM"];
    for (var element in initalstocks) {
      Response mydata = await get(Uri.parse(
          "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=$element&interval=5min&apikey=RTILMV6RV0R20DKC"));
      Map decodeBodyData = jsonDecode(mydata.body);
      Map body_data = decodeBodyData["Time Series (5min)"];
      String open = body_data[0]["1. open".toString()];
      print(open);
      stockname.add(Stock(
        id: i.toString(),
        name: element,
        value: 1,
        change: 2,
      ));
      i += 1;
    }
  }

  final List<Stock> stockname = [];

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        const SizedBox(
          height: 1,
          width: double.infinity,
          child: DecoratedBox(
            decoration: BoxDecoration(color: Colors.grey),
          ),
        ),
        Column(
          children: stockname.map((stx) {
            return Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      height: 100,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        stx.name,
                        style: const TextStyle(
                          color: Colors.white,
                        ),
                      ),
                    ),
                    Column(
                      children: [
                        Text(
                          '$${stx.value.toString()}',
                          style: const TextStyle(
                            color: Colors.white,
                          ),
                        ),
                        Text(
                          '$${stx.change.toString()}',
                          style: const TextStyle(
                            color: Colors.white,
                          ),
                        ),
                      ],
                    )
                  ],
                ),
                const SizedBox(
                  height: 1,
                  width: double.infinity,
                  child: DecoratedBox(
                    decoration: BoxDecoration(color: Colors.grey),
                  ),
                ),
              ],
            );
          }).toList(),
        ),
      ],
    );
  }
}

Tis is class constructor i use to map data into the widgets.


import 'package:flutter/material.dart';

class Stock {
  var id;
  var name;
  var value;
  var change;
  Stock({
    this.id,
    this.name,
    this.value,
    this.change,
  });
}

2

Answers


  1. Trying out your url

    https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=TCS&interval=5min&apikey=RTILMV6RV0R20DKC
    

    the result looks like this (partly omitted for brevity):

    {
        "Meta Data": {
            "1. Information": "Intraday (5min) open, high, low, close prices and volume",
            "2. Symbol": "TCS",
            "3. Last Refreshed": "2023-01-26 19:05:00",
            "4. Interval": "5min",
            "5. Output Size": "Compact",
            "6. Time Zone": "US/Eastern"
        },
        "Time Series (5min)": {
            "2023-01-26 19:05:00": {
                "1. open": "5.1200",
                "2. high": "5.1200",
                "3. low": "5.1200",
                "4. close": "5.1200",
                "5. volume": "500"
            },
            "2023-01-26 16:00:00": {
                "1. open": "5.0900",
                "2. high": "5.1100",
                "3. low": "5.0800",
                "4. close": "5.1100",
                "5. volume": "11474"
            },
            "2023-01-26 15:55:00": {
                "1. open": "5.0700",
                "2. high": "5.1100",
                "3. low": "5.0700",
                "4. close": "5.0900",
                "5. volume": "8234"
            }
        }
    }
    

    The thing is, the first data point you try to get is not on:

    jsonDecode(mydata.body)["Time Series (5min)"][0]["1. open"],
    

    but on

    jsonDecode(mydata.body)["Time Series (5min)"]["2023-01-26 19:05:00"]["1. open"],
    

    "Time Series (5min)" is not a list but a map.

    Because the keys seem to be dynamic dates it’s harder to hardcode it, but this might work:

    jsonDecode(mydata.body)["Time Series (5min)"].values.toList()[0]["1. open"],
    
    Login or Signup to reply.
  2. Problem is with your fetch is not successful as it is returing null,

    Response mydata = await get(Uri.parse(
              "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=$element&interval=5min&apikey=RTILMV6RV0R20DKC"));
          Map decodeBodyData = jsonDecode(mydata.body); //👈 try to print your decodeBodyData make sure it is not null
          Map body_data = decodeBodyData["Time Series (5min)"]//👈 Only then this will work
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search