Я пытался получить данные из api и отобразить их в DropDownButton Я хочу получить название страны и идентификатор страны из api
Мой код:
Моя функция получения
List country_data = List();
String countryid;
Future<String> country() async {
final prefs = await SharedPreferences.getInstance();
final key = 'session_id';
final value = prefs.get(key ) ?? 0;
var res = await http.get(
Uri.encodeFull("http://husam.from-ar.com/api/api-ad/en/1"),
headers: {"Accept": "application/json",
"Authorization" : "$value",
}); //if you have any auth key place here...properly..
var resBody = await json.decode(res.body);
setState(() {
country_data = resBody;
});
return "Sucess";
}
@override
void initState() {
super.initState();
this.country();
}
столбец отображения:
Column(
children: <Widget>[
DecoratedBox(
decoration: BoxDecoration(
border: new Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(5.0)),
child: Padding(
padding: EdgeInsets.fromLTRB(10, 5, 0, 0),
//Why you have used Stack ??????
//B'coz it make clickable to whole decorated Box!!!! as you can click anywhere for dropdown !!!
child: Stack(
children: <Widget>[
//Country Text
Text(
"Country: ",
style: TextStyle(
fontSize: 13.0,
),
),
//Dropdown that has no loine beneath
DropdownButtonHideUnderline(
child:
//starting the dropdown
DropdownButton(
items: country_data.map((item) {
return new DropdownMenuItem(
child: new Text(
item['countries']['name'], //Names that the api dropdown contains
style: TextStyle(
fontSize: 13.0,
),
),
value: item['countries']['id'].toString()
//e.g India (Name) and its ID (55fgf5f6frf56f) somethimg like that....
);
}).toList(),
onChanged: (String newVal) {
setState(() {
countryid = newVal;
print(countryid.toString());
});
},
value: countryid, //pasing the default id that has to be viewed... //i havnt used something ... //you can place some (id)
),
)
],
),
)),
],
),
ответ json с сервера api:
{
"products": [],
"productStatus": [
{
"name": "OLD",
"id": 1
}
],
"countries": [
{
"name": "Turkey",
"id": 1
},
{
"name": "Syria",
"id": 2
}
],
"currencies": [
{
"name": "DOLLAR",
"id": 1
}
],
"units": [
{
"name": "KG",
"id": 1
},
{
"name": "liter",
"id": 2
}
],
"addresses": []
}
У меня не было ошибок, мой код запускается без ошибок, пожалуйста, попробуйте мне помочь и большое спасибо за любой вопрос, просто оставьте комментарий