【发布时间】:2021-03-30 00:32:47
【问题描述】:
我正在用颤振写一个注册表单,一旦用户按下“注册”按钮,我就会将信息发送到后端,并得到响应。如果响应是写入用户失败(重复电子邮件、无效数据),我想将响应文本与 AlertDialog 一起显示在屏幕上。
我的问题是,当我将响应存储在变量中然后检查它们的值时,它们似乎直到需要它们之后才更新。
我获取 api 响应的函数如下所示:
int apiResponseCode;
String apiResponseText;
void createUser(xxxxx) async {
final http.Response response = await http.post('xxxxxx', headers: <String, String>{'Content-Type': 'application/json; charset=UTF-8',},
body: jsonEncode(<String, String>{
"data": "xxxxxx",
}),
);
if (response.statusCode == 200) {
Map<String, dynamic> resp = jsonDecode(response.body);
setState(() { this.apiResponseCode = resp['response_code']; this.apiResponseText = resp['response_text']; });
}
}
然后我的表单提交按钮小部件如下所示:
RoundedButton(
text: "SIGNUP",
press: () {
createUser(xxxxxxxx);
if (this.apiResponseCode != 1) {
showDialog(
context: context,
child: AlertDialog(
title: Text(
"Oops! Please Fix the error below! ",
textAlign: TextAlign.center,
style: TextStyle(color: kPrimaryColor),
),
content: Text(
this.apiResponseText,
textAlign: TextAlign.center,
style: TextStyle(color: kPrimaryColor),
),
actions: [
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"OK",
textAlign: TextAlign.center,
style: TextStyle(
color: kPrimaryLightTextColor),
)),
],
),
);
} else {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return TwoStepValidationScreen();
},
),
);
}
}),
第一次按下提交按钮时,this.apiResponseText 和 this.apiResponseCode 为空/空,然后第二次按下按钮时,变量保持它们之前应该具有的值。例如,如果第一次按下按钮时,api 响应有效,则屏幕将输出失败。但是第二次按下按钮时,apiResponse 无效(因为已经创建了该用户),但该按钮适用于他们的用户并且他们被导航到下一页。
如果有人知道为什么在调用函数之后才存储响应,将不胜感激!
【问题讨论】:
-
您必须将此代码
press: () { createUser(xxxxxxxx);更改为press: () async { await createUser(xxxxxxxx); -
很高兴知道它对您有所帮助。快乐编码!!!