将 API 返回的错误信息显示到 Flutter UI 中

问题描述

将 API 返回的错误消息显示Flutter UI 中。

我是 Flutter 的新手。我的 Laravel API 返回以下响应,我成功接收到响应,但我无法找到在 UI 中显示这些消息的方法,我使用 Flushbar 来显示消息。请帮忙。

{
 "data":{
  "errors": {
    "email": [
        "The email has already been taken."
    ],"password": [
        "The password must be at least 6 characters.","The password confirmation does not match."
    ]
  }
 }
}

解决方法

var res = {
  "data":{
    "errors": {
      "email": [
        "The email has already been taken."
      ],"password": [
        "The password must be at least 6 characters.","The password confirmation does not match."
      ]
    }
  }
};

res["data"]["errors"].forEach((key,messages) { 
  if ("email" == key) {
    // show email errors like this
    for (var message in messages) {
      // Use your Flushbar here to show the error message
    }
  } else if ("password" == key) {
    // show password erros like this 
    for (var message in messages) {
      // Use your Flushbar here to show the error message
    }
  }
});

编辑
为了更简短,您可以将您的消息组合成这样

String combinedMessage = "";

res["data"]["errors"].forEach((key,messages) {      
  for (var message in messages) combinedMessage = combinedMessage + "- $message\n";
  // Use your Flushbar here to show combinedMessage variable
});