Я пытаюсь проанализировать данные JSON во Flutter, и он работает нормально. Но когда некоторые данные пусты или равны нулю, они не работают и выдают ошибку.
import 'dart:convert';
GetFollowing getFollowingFromJson(String str) => GetFollowing.fromJson(json.decode(str));
class GetFollowing {
List<Content> content;
int count;
bool success;
String error;
GetFollowing({
this.error,
this.content,
this.count,
this.success,
});
factory GetFollowing.fromJson(Map<String, dynamic> json) => GetFollowing(
error: json["error"],
content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
count: json["count"],
success: json["success"],
);
}
class Content {
int uid;
int following;
String name;
String profilePhoto;
String baseLocation;
String registrationDate;
String country;
Content({
this.uid,
this.following,
this.name,
this.profilePhoto,
this.baseLocation,
this.registrationDate,
this.country,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
uid: json["uid"] ?? null,
following: json["following"] ?? null,
name: json["name"] ?? null,
profilePhoto: json["profile_photo"] ?? null,
baseLocation: json["base_location"] ?? null,
registrationDate: json["registration_date"] ?? null,
country: json["country"] ?? null,
);
}
Вот пример данных.
Сценарий
{«ошибка»: «Запись не найдена.», «Успех»: false}
Сценарий
{
"content": [{
"uid": 34,
"following": 35,
"name": "Sadi",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}, {
"uid": 34,
"following": 37,
"name": "Sameer",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}, {
"uid": 34,
"following": 36,
"name": "Simran",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}],
"count": 3,
"success": true
}
Я получаю сообщение об ошибке, если содержимое пустое или пустое, значит, синтаксический анализ не завершен и выдает ошибку.
Exception Caught: NoSuchMethodError: The method '[]' was called on null.