Search code examples
flutterdartlaravel-api

Display error messages returned from API into Flutter UI


Display error messages returned from API into Flutter UI.

I am new to Flutter. My Laravel API returns the following response, I am successfully receiving the response but I am unable to find a way to display these messages in UI, I am using Flushbar to display messages. Please help.

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

Solution

  • 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
        }
      }
    });
    

    Edit
    To be shorter, you can combine your messages as one like this

    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
    });