0

我正在尝试学习和使用 API,我正在使用 Tiingo Stock 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 密钥。

4

1 回答 1

1

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

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

解决您的问题

       FlatButton(
          onPressed: () async {
            FocusScope.of(context).unfocus();
            await getPrice(ticker.text);
            setState(() {
              
            });
          },
          child: Text('Submit')
        ),

所以setState在API调用完成后调用该方法。

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

于 2020-07-03T05:24:54.200 回答