Почему приложение на Flutter не получает данные с сервера? Подскажите, где ошибка
Такая проблема: хочу разобраться, почему мое приложение во Flutter не получает данные с сервера с помощью библиотеки HTTP? Я использую API [Geography API][1]
[1]: https://apilayer.com/marketplace/geo-api?e=Sign%20In&l=Success&e=Sign%20In&l=Success# , чтобы получить информацию о стране: название (name), площадь(area), численность населения (population), язык(demonym) и регион (region). Ответ в JSON-формате должен получиться таким:
```
[
{
"alpha2code": "DE",
"alpha3code": "DEU",
"alt_spellings": [
"DE",
"Federal Republic of Germany",
"Bundesrepublik Deutschland"
],
"area": 357114.0,
"borders": [
"AUT",
"BEL",
"CZE",
"DNK",
"FRA",
"LUX",
"NLD",
"POL",
"CHE"
],
"calling_codes": [
"49"
],
"capital": "Berlin",
"currencies": [
{
"code": "EUR",
"name": "Euro",
"symbol": "\u20ac"
}
],
"demonym": "German",
"flag": "http://assets.promptapi.com/flags/DE.svg",
"gini": 28.3,
"languages": [
{
"iso639_1": "de",
"iso639_2": "deu",
"name": "German",
"native_name": "Deutsch"
}
],
"latitude": 51.0,
"longitude": 9.0,
"name": "Germany",
"native_name": "Deutschland",
"numeric_code": "276",
"population": 81770900,
"region": "Europe",
"regional_blocs": [
{
"acronym": "EU",
"name": "European Union"
}
],
"subregion": "Western Europe",
"timezones": [
"UTC+01:00"
],
"top_level_domains": [
".de"
]
}
]```
Но почему-то при этом вылезает ошибка ClientException. Помогите найти ошибку, сам все перепробовал, не нашел. Вот код моей модели:
```class CountryByName{
final String name;
final double area;
final int population;
final String demonym;
final String region;
CountryByName(
{required this.name,
required this.area,
required this.population,
required this.demonym,
required this.region
}
);
factory CountryByName.fromJson(Map<String, dynamic> json){
return CountryByName(
name: json['']['']['name'],
area: json['']['']['area'],
population: json['']['']['population'],
demonym: json['']['']['demonym'],
region: json['']['']['region']
);
}
}```
Это UseCase, который получает данные с сервера:
```class GetCountryByNameUseCase{
Future<CountryByName> execute(String countryName) async {
final url = 'https://api.apilayer.com/geo/country/name/$countryName';
final apiKey = 'мой ключ';
final response = await http.get(Uri.parse(url), headers: <String, String>{
'Authorization': 'Bearer $apiKey',
});
if(response.statusCode==200){
return CountryByName.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load data');
}
}
}```
А это один из моих дочерних виджетов, где собственно и происходит запрос и вывод данных на экран:
```class CoutryInfoMainScreen extends StatefulWidget {
const CoutryInfoMainScreen({super.key});
@override
State<CoutryInfoMainScreen> createState() => _CoutryInfoMainScreenState();
}
class _CoutryInfoMainScreenState extends State<CoutryInfoMainScreen> {
var getCountryByNameUseCase=GetCountryByNameUseCase();
late CountryByName countryByName;
String name='';
int population=0;
double area=0.0;
String demonym='';
String region='';
String error='';
@override
void initState(){
getData();
super.initState();
}
Future<void> getData() async{
try {
countryByName=await getCountryByNameUseCase.execute('Germany');
setState(() {
name=countryByName.name;
area=countryByName.area;
population=countryByName.population;
demonym=countryByName.demonym;
region=countryByName.region;
});
} catch (e) {
setState(() {
error=e.toString();
});
}
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('$name', style: TextStyle(fontSize: 40),),
Text('City name', style: TextStyle(fontSize: 30),),
Padding(padding: EdgeInsets.symmetric(vertical: 10.0),),
Card(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Area:', style: TextStyle(fontSize: 20)),
Text('$area', style: TextStyle(fontSize: 20))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Population:', style: TextStyle(fontSize: 20)),
Text('$population', style: TextStyle(fontSize: 20))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Demonym:', style: TextStyle(fontSize: 20)),
Text('$demonym', style: TextStyle(fontSize: 20))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Region:', style: TextStyle(fontSize: 20)),
Text('$region', style: TextStyle(fontSize: 20))
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Error:', style: TextStyle(fontSize: 20)),
Text('$error', style: TextStyle(fontSize: 20))
],
),
],
),
)
],
);
}
}```