如何为我的下拉添加自定义选项



所以现在我有一个从API获取的下拉列表。这是我做的

  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";
  }

那么,这就是我在下拉菜单上使用它的方式

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, ),),

一切正常工作,但是现在我想将All Category添加到下拉列表中,我该如何实现?预先感谢

您的下拉餐点项目是一个列表,因此您可以使用.. 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, ),),
  1. 您可以使用级联操作员
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, ),),

此解决方案将具有"所有类别"项目的效果。

  1. 您可以在getswdata((中添加"所有类别"项目。
   ... 
   setState(() {
      data = List();
      data.add({
         'categoryName': 'All Categories', 
         'categoryId': 'AllCategories',
      });
      data.addAll(resBody);
    });
    ...

我会推荐第二种方法,您会得到更好的可读代码。

最新更新