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
Trying out your url
the result looks like this (partly omitted for brevity):
The thing is, the first data point you try to get is not on:
but on
"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:
Problem is with your fetch is not successful as it is returing
null
,