在按下按钮两次之前,状态不会更新



我正在尝试学习和使用API,我正在使用Tiingo股票API来获取股票信息。我当前的应用程序是:

class _StockAppState extends State<StockApp> {

String out = "Enter Ticker and press Submit";
Map<String,String> headers = {
'Content-Type': 'application/json',
'Authorization' : <API KEY REMOVED>
};
void getPrice(String tick) async {
if(tick == ""){
out = "Enter Ticker and press Submit";
}else{
Response rep = await get('https://api.tiingo.com/tiingo/daily/$tick/prices', headers: headers);
if(rep.statusCode ==  200){  
List data = json.decode(rep.body);
Map dataS = data[0];
out = "Price: ${dataS['close']}";
}else{
out = "Error";
}
}
}
@override
void initState() { 
super.initState();  
}
TextEditingController ticker = new TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Stock App'),),
body: Column(
children: <Widget>[
TextField(
controller: ticker,
textAlign: TextAlign.left,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Enter Ticker',
hintStyle: TextStyle(color: Colors.grey),
),
),
FlatButton(
onPressed: () async {
FocusScope.of(context).unfocus();
setState(() {
getPrice(ticker.text);
});
},
child: Text('Submit')
),
Text(out),  
],
),
);
}
}

因此,基本上,当您输入股票代码并按提交时,该应用程序将更改"out"字符串var以显示股票价格。但是要更新应用程序,我必须按两次提交。

谁能帮忙?

PS:出于安全原因,我删除了我的API密钥。

这是因为您的setState方法中有异步方法。 将同步调用setState方法。

所以这里的问题是当执行setState并且帧刷新时,来自 api 的数据尚未到达,它向您显示旧数据。当您再次单击该按钮时,您的out变量具有新数据(从第一次单击开始(,这些数据将显示在屏幕上,并且将再次调用API。

解决您的问题

FlatButton(
onPressed: () async {
FocusScope.of(context).unfocus();
await getPrice(ticker.text);
setState(() {

});
},
child: Text('Submit')
),

因此,在 API 调用完成后调用setState方法。

要了解有关异步/等待的更多信息,请观看此视频:https://www.youtube.com/watch?v=SmTCmDMi4BY

最新更新