5

Trying to create an if statement that checks if an API returns 'items' containing data

Here is the API url, you can see that items is empty for that specific data query https://data.food.gov.uk/food-alerts/id?since=2021-01-04T00:00:00Z

My code is below, been trying to see if I can check 'items' to see if it is null, as well as checking for its length and see if it equals 0 but has not worked so far

class AllergyAlert {
  final String title;

  AllergyAlert({this.title});

  factory AllergyAlert.fromJson(Map<String, dynamic> json) {
    if (json['items'] == null) {
      return AllergyAlert(
        title: 'No new allergy alerts',
      );
    } else {
      return AllergyAlert(
        title: json['items'][0]['title'],
      );
    }
  }
}

2 Answers 2

4

You can try this

return AllergyAlert(
   title: json['items'].isEmpty ? 'No new allergy alerts' : json['items'][0]['title'],
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you solved the issue I was having and the ternary operator made the code even cleaner, appreciate that
0

First create a class to decode your json string with. You can paste your json here Quicktype

This can then be used with a FutureBuilder to load the data. Here is a full example Solution

Then after that you will just use the defined names to check. Like:

class Allergen {
Allergen({
    this.meta,
    this.items,
});

final Meta meta;
final List<dynamic> items;

factory Allergen.fromJson(Map<String, dynamic> json) => Allergen(
    meta: Meta.fromJson(json["meta"]),
    items: List<dynamic>.from(json["items"].map((x) => x)),
);

Map<String, dynamic> toJson() => {
    "meta": meta.toJson(),
    "items": List<dynamic>.from(items.map((x) => x)),
};
}

class Meta {
Meta({...//more here

you can just check the length of the list

Allergen.items.length==0?//Do This://Else This

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.