У меня постоянно возникают сложности в понимании как парсить разные JSON объекты, может быть есть у кого источник для познания? Вот конкретный JSON:
{
"success": true,
"data": {
"country": [
{
"id": "67",
"name": "Algeria",
"is_real": "1",
"leagues": "https://livescore-api.com/api-client/leagues/list.json?key=o77eB07ZqirxyShu&secret=f8bK5NOObpYQn23Lab0Lc7LCpcaY5rsl&country=67",
"scores": "https://livescore-api.com/api-client/scores/live.json?key=o77eB07ZqirxyShu&secret=f8bK5NOObpYQn23Lab0Lc7LCpcaY5rsl&country=67",
"federation": {
"id": "3",
"name": "CAF"
},
"national_team": {
"id": "1528",
"name": "Algeria",
"stadium": "Stade du 5 Juillet 1962",
"location": "Stade du 5 Juillet 1962"
}
}
]
}
}
import 'dart:convert';
Country countryFromJson(String str) => Country.fromJson(json.decode(str));
String countryToJson(Country data) => json.encode(data.toJson());
class Country {
Country({
required this.success,
required this.data,
});
bool success;
Data data;
factory Country.fromJson(Map<String, dynamic> json) => Country(
success: json["success"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"success": success,
"data": data.toJson(),
};
}
class Data {
Data({
required this.country,
});
List<CountryElement> country;
factory Data.fromJson(Map<String, dynamic> json) => Data(
country: List<CountryElement>.from(json["country"].map((x) => CountryElement.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"country": List<dynamic>.from(country.map((x) => x.toJson())),
};
}
class CountryElement {
CountryElement({
required this.id,
required this.name,
required this.isReal,
required this.leagues,
required this.scores,
required this.federation,
required this.nationalTeam,
});
String id;
String name;
String isReal;
String leagues;
String scores;
Federation federation;
NationalTeam nationalTeam;
factory CountryElement.fromJson(Map<String, dynamic> json) => CountryElement(
id: json["id"],
name: json["name"],
isReal: json["is_real"],
leagues: json["leagues"],
scores: json["scores"],
federation: Federation.fromJson(json["federation"]),
nationalTeam: NationalTeam.fromJson(json["national_team"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"is_real": isReal,
"leagues": leagues,
"scores": scores,
"federation": federation.toJson(),
"national_team": nationalTeam.toJson(),
};
}
class Federation {
Federation({
required this.id,
required this.name,
});
String id;
String name;
factory Federation.fromJson(Map<String, dynamic> json) => Federation(
id: json["id"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}
class NationalTeam {
NationalTeam({
required this.id,
required this.name,
required this.stadium,
required this.location,
});
String id;
String name;
String stadium;
String location;
factory NationalTeam.fromJson(Map<String, dynamic> json) => NationalTeam(
id: json["id"],
name: json["name"],
stadium: json["stadium"],
location: json["location"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"stadium": stadium,
"location": location,
};
}
функция с которой всегда проблемы:
Future<Map<String, dynamic>> fetchCountries() async{
final url = Uri.parse('https://livescore-api.com/api-client/countries/list.json?&key=$_apiKey&secret=$_secretApiKey');
final response = await http.get(url);
if(response.statusCode == 200) {
final parsedJson = jsonDecode(response.body) as Map<String, dynamic>;
final countries = Country.fromJson(parsedJson);
print(countries.runtimeType);
return countries as Map<String, dynamic>;
}else{
throw Exception('SHIT!!!');
}
}
Пытаюсь отобразить название страны, но получаю ошибку Unhandled Exception: type 'Null' is not a subtype of type 'String'
class CountriesWidget extends StatefulWidget {
const CountriesWidget({Key? key}) : super(key: key);
@override
State<CountriesWidget> createState() => _CountriesState();
}
class _CountriesState extends State<CountriesWidget> {
final apiClient = ApiClient();
@override
void initState() {
super.initState();
apiClient.fetchCountries();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: apiClient.fetchCountries(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, index) {
return GestureDetector(
// onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (context) => LegauesWidget(countryName: snapshot.data[index].name))),
child: Card(
borderOnForeground: true,
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white, width: 2),
borderRadius:
BorderRadius.all(Radius.circular(10.0))),
color: Color.fromRGBO(28, 27, 31, 1),
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10.0),
bottomLeft: Radius.circular(10.0),
),
child: Row(
children: [
/* Container(
height: 90,
width: 120,
child: FittedBox(
child: SvgPicture.network(
snapshot.data[index].flag),
)),*/
SizedBox(
width: 10,
),
Flexible(
child: Text("${snapshot.data[index].data.country.name}", style: countriesStyle(),))
],
),
),
),
);
}),
);
} else {
return Center(
child: Text('Нет данных'),
);
}
} else if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else {
return Center(
child: Icon(
Icons.error,
color: Colors.white,
),
);
}
});
}
}