简体   繁体   English

如何等待 flutter (dio) 中的响应?

[英]How can I wait for response in flutter (dio)?

I am doing a get request on the server and on the basis of response status I wanna show a toast on the screen before popping the screen.我正在服务器上执行获取请求,并且根据响应状态,我想在弹出屏幕之前在屏幕上显示祝酒词。 But because of async/await the data is null and toast cannot be displayed and screen gets popped before.但是由于 async/await 数据是 null 并且无法显示 toast 并且之前弹出屏幕。 I want to wait for the response message to be shown in toast and then pop the activity.我想等待响应消息显示在 toast 中,然后弹出活动。 在这个按钮之后,我想展示吐司。 吐司消息。

Instead of using then, use await.不要使用 then,而是使用 await。 It is lot more intuitive.它更直观。

onPressed: () async {
    final response = await submitData();
    // here you can show toast or pop or whatever you wanna do
  },


Future<String> submitData() async {
  final resp = await register();
  final statusCode = resp.statusCode;
  if (statusCode == 400) {
    return 'something went wrong';
  } else if (statusCode == 200) {
    return 'success';
  } else {
    return 'something else';
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM