Home > Mobile >  How to put a conditional in json post request flutter
How to put a conditional in json post request flutter

Time:05-24

I have this payload that I need to send to a server

"members": [
 {
 "names": "ben",
 "date-of-birth": "1978-01-01",
 "gender": "Male",
 "surname": "surname",
 "role": "Partner",
 "total-cut": "100.00"
 }
 ],

Only thing is at times there are no members, and following this am not supposed to send the array at all, it should just be nothing at all, no members. For clarification, this is an example only, think there is a members object, like the above, schools object, courses object, only at times some of this come up empty and consequently I should omit the empty object entirely. For example, in the below, if there are no members,,

{
"members": [
 {
 "names": "ben",
 "date-of-birth": "1978-01-01",
 "gender": "Male",
 "surname": "surname",
 "role": "Partner",
 "total-cut": "100.00"
 }
 ],
"courses": [
 {
 "name": "ben",
 "number": "32",
 "teacher": "Russ",
 "cut": "10.00"
 }
 ],
}

how can i create a conditional that omits the members and leaves courses only

{
"courses": [
 {
 "name": "ben",
 "number": "32",
 "teacher": "Russ",
 "cut": "10.00"
 }
 ],
}

For context this is a post request

CodePudding user response:

You should declare the parameter members to be optional in your API, then you have no need to send this parameter.

CodePudding user response:

you can do the following

final List members = [];
final List courses = [];
final map = {
  if (members.isNotEmpty)
    'members': [
      for (final member in members)
        {
          "names": "ben",
          "date-of-birth": "1978-01-01",
          "gender": "Male",
          "surname": "surname",
          "role": "Partner",
          "total-cut": "100.00"
        }
    ],
  if (courses.isNotEmpty)
    'courses': [
      for (final course in courses)
        {
          "name": "ben",
          "number": "32",
          "teacher": "Russ",
          "cut": "10.00"
        }
    ]
};

you can use if statement inside a map or a list in flutter, also, if you want to multiple fields if a condition is met

final map2 = {
  if(true)...{
    'name': 'name',
    'age': '12'
  } else ...{
    'name': 'NO NAME',
    'age': 'NO AGE'
  }
};
  • Related