0

将 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."
    ]
  }
 }
}
4

1 回答 1

1
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
});
于 2020-12-21T15:09:34.030 回答