Reputation: 454
I have an Api Which I want to show in my drop down menu of flutter app.
I am able to get lists in simple Text widget but not able to fetch in DropDownButton.
Here is sample of my code
_getAllCategories() async {
var categories = await _categoryService.getCategories();
var _list = json.decode(categories.body);
List<Category> results = [];
_list['data'].forEach((data) {
var model = Category();
model.id = data["id"];
model.name = data["categoryName"];
model.icon = data["categoryIcon"];
results.add(model);
});
if (mounted) {
setState(() {
_categoryList = results;
});
}
}
and I am getting my result using
ListView.builder(
itemCount: _categoryList.length,
itemBuilder: (context, index){
return Text(_categoryList[index].name,style: TextStyle(fontSize: 25),);
},
),
Upvotes: 1
Views: 4589
Reputation: 7640
You can try a simple dropdown widget like this:
List<Category> _categoryList = List<Category>();
Category dropdownValue;
@override
Widget build(BuildContext context) {
return DropdownButton<Category>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (Category newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: _categoryList.map<DropdownMenuItem<Category>>((Category value) {
return DropdownMenuItem<Category>(
value: value,
child: Text(value.name),
);
}).toList(),
);
}
}
class Category {
String name;
String icon;
int id;
}
Upvotes: 2