How to check if JSON array is empty in Flutter

Viewed 5349

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

You can try this

return AllergyAlert(
   title: json['items'].isEmpty ? 'No new allergy alerts' : json['items'][0]['title'],
);

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
Related