【问题标题】:State does not update until button is pressed twice在按下按钮两次之前状态不会更新
【发布时间】:2020-10-23 19:01:41
【问题描述】:

我正在尝试学习和使用 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 以显示股票价格。但是要更新应用程序,我必须按两次提交。

有人可以帮忙吗?

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

【问题讨论】:

    标签: flutter dart tiingo


    【解决方案1】:

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

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

    解决你的问题

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-30
      • 2022-07-08
      • 2020-08-20
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      相关资源
      最近更新 更多