首页 > 解决方案 > 如何为我的下拉菜单添加自定义选项?

问题描述

所以现在我有一个从 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到我的下拉列表中,我该如何实现?提前致谢

标签: flutterdart

解决方案


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

推荐阅读