[英]How to add custom option for my dropdown?
So for now i have a dropdown that i fetch from api.所以现在我有一个从 api 获取的下拉列表。 Here is what i do这是我所做的
Future<String> getSWData() async {
var res = await http.get(
Uri.encodeFull(Configuration.url + "api/getCategories"),
headers: {"Accept": "application/json"});
var resBody = json.decode(res.body);
setState(() {
data = resBody;
});
print(data);
return "Sucess";
}
then here is how i use it on dropdown那么这是我如何在下拉列表中使用它
DropdownButtonHideUnderline(
child: new DropdownButton(
hint: new Text("Choose Category"),
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['categoryName']),
value: item['categoryId'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
mySelection = newVal;
});
},
value: _mySelection, ),),
Everything is working fine, but now i want to add All Category
to my dropdown as an option, how can i achieve that ?一切正常,但现在我想将All Category
作为选项添加到我的下拉列表中,我该如何实现? thanks in advance提前致谢
Your DropdownButton items is a list, so you can add to that list using ..add您的 DropdownButton 项目是一个列表,因此您可以使用 ..add 添加到该列表中
DropdownButtonHideUnderline(
child: new DropdownButton(
hint: new Text("Choose Category"),
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['categoryName']),
value: item['categoryId'].toString(),
);
}).toList()
..add(DropdownMenuItem(child: Text("All Category"), value: 'allcategory')),
onChanged: (newVal) {
setState(() {
mySelection = newVal;
});
},
value: _mySelection, ),),
DropdownButtonHideUnderline(
child: new DropdownButton(
hint: new Text("Choose Category"),
items: data..add({
'categoryName': 'All Categories',
'categoryId': 'AllCategories',
}).map((item) {
return new DropdownMenuItem(
child: new Text(item['categoryName']),
value: item['categoryId'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
mySelection = newVal;
});
},
value: _mySelection, ),),
this solution will have the effect that "All Categories" item will be last.此解决方案将具有“所有类别”项目将在最后的效果。
...
setState(() {
data = List();
data.add({
'categoryName': 'All Categories',
'categoryId': 'AllCategories',
});
data.addAll(resBody);
});
...
I would recommend the second approach, you get better readable code.我会推荐第二种方法,你会得到更好的可读代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.