我有一个返回json对象的api。
json对象:
{
"Global Quote": {
"01. symbol": "NSE:STRTECH",
"02. open": "88.5000",
"03. high": "91.5500",
"04. low": "85.7000",
"05. price": "90.0500",
"06. volume": "1240424",
"07. latest trading day": "2020-03-06",
"08. previous close": "93.1000",
"09. change": "-3.0500",
"10. change percent": "-3.2760%"
}
}
我上的课:
class Stock {
GlobalQuote globalQuote;
Stock({this.globalQuote});
factory Stock.fromJson(Map<String, dynamic> parsedJson) {
return Stock(globalQuote: GlobalQuote.fromJson(parsedJson['globalQuote']));
}
}
class GlobalQuote {
String symbol;
double openPrice;
double high;
double low;
int volume;
String change;
String changePercent;
String latestTradingDay;
GlobalQuote(
{this.symbol,
this.openPrice,
this.high,
this.low,
this.volume,
this.change,
this.changePercent,
this.latestTradingDay});
factory GlobalQuote.fromJson(Map<String, dynamic> json) {
return GlobalQuote(
symbol: json['01. symbol'],
openPrice: json['02. open'],
high: json['03. high'],
low: json['04. low'],
volume: json['06. volume'],
change: json['09. change'],
changePercent: json['10. change percent'],
latestTradingDay: json['07. latest trading day']);
}
}
这是我遵循中级文章https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51
之后想到的我正在尝试显示从api调用获得的数据,但是出现以下错误:
type 'Future<GlobalQuote>' is not a subtype of type 'Future<Stock>' of 'function result'
显示数据的代码:
import 'package:flutter/material.dart';
import 'services.dart';
import 'Stock.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Future<Stock> futureStock;
@override
void initState() {
super.initState();
futureStock = fetchData();
}
Future<Stock> fetchData() async {
final response = await http.get(
"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=NSE:STRTECH&apikey=$apiKey");
if (response.statusCode == 200)
{
print("Response:${response.body}");
print("Decoded:${json.decode(response.body)}");
return Stock.fromJson(json.decode(response.body));
}
else
throw Exception('Failed to get Stock');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("SIFA"),
),
body: Center(
child: FutureBuilder<Stock>(
future: futureStock,
builder: (context, snapshot) {
if (snapshot.hasData) {
print("->->->->->${snapshot.data.globalQuote.symbol}");
return Text(
"${snapshot.data.globalQuote.symbol}\nlow:${snapshot.data.globalQuote
.low}\nhigh:${snapshot.data.globalQuote.high}\nOpen Price:${snapshot
.data.globalQuote.openPrice}\nChange Percent:"
"${snapshot.data.globalQuote.changePercent}");
}
else if (snapshot.hasError) return Text("${snapshot.error}");
return CircularProgressIndicator();
}),
),
);
}
}
我要进行哪些更改才能使数据显示在应用程序中?