如何在 flutter(dart) 中正确接收来自服务器的响应?

问题描述 投票:0回答:1

我无法在 flutter 中正确处理来自服务器的响应,在数据库中成功创建了用户,在 postman 应用程序中我也得到了来自服务器的响应:{"success":true},但由于某种原因连接错误显示在控制台中,尽管从表中的颤动也成功创建了用户: Future _sendLanguages(List selectedLanguages, String firstName, String lastName, String email, String password) async { 最终 url = Uri.parse('http://localhost/create_user.php'); 最终回应 = await http.post( 网址, 标头:{“Content-Type”:“application/json”}, 正文:jsonEncode({ 'first_name':widget.firstName, 'last_name':widget.lastName, '电子邮件':widget.email, '密码':widget.password, '语言':_selectedLanguages.map((language) => language.code).toList(), }), ); 最终 jsonResponse = json.decode(response.body); 如果(jsonResponse [“成功”]){ Navigator.pop(上下文); } }

我尝试将 if 更改为 succes == true ,但这也不起作用,dart 没有正确处理来自服务器的响应

flutter dart user-registration jsonresponse server-response
1个回答
0
投票

我认为您遇到的错误(请分享错误日志)与响应无关。但您可以检查状态代码并查看其行为:

Future _sendLanguages(List selectedLanguages, String firstName, String lastName, String email, String password) async { 
final url = Uri.parse('http://localhost/create_user.php'); 
final response = await http.post(
  url,
  headers: {"Content-Type": "application/json"},
  body: jsonEncode({
    'first_name': widget.firstName,
    'last_name': widget.lastName,
    'email': widget.email,
    'password': widget.password,
    'languages': _selectedLanguages.map((language) => language.code).toList(),
  }),
);


print('response: ${response.body}'); // this line shows you the response

if (response.statusCode == 200) {
  final jsonResponse = json.decode(response.body);
  if (jsonResponse["success"] == true) {
    Navigator.pop(context);
  }
} else {
  print('Request failed with this status code: ${response.statusCode}.');
 }
}

如果响应代码不是 200,则您的请求有问题(如果您检查了正确的 url 和标头以及您的正文)。

如果响应码是200,你又遇到问题,注意这个

print('response: ${response.body}');
看看你是否以正确的方式解析。 如果你还有问题,你应该说更多的细节来帮助你。

快乐编码。

© www.soinside.com 2019 - 2024. All rights reserved.