如何在Flutter中填充下拉列表以及如何显示下拉列表中的选定项目

时间:2020-04-12 10:17:30

标签: flutter

我有一个API,该API返回如下的JSON数据

[
    {
        "_id": "5e706f8b0fffe742ec285463",
        "NAME": "CMP1",

    }
]

我需要使用上述JSON数据创建动态下拉菜单,并显示下拉列表中的选定项。

用于获取数据的跟踪功能

Future <String>getCompanies  () async {
    final response = await http.get(MasterServices.getCompaniesURL());
    if (response.statusCode == 200) {
      // If the server returns an OK response, then parse the JSON.
      List responseJson = json.decode(response.body);
      Company_Model company_model= new Company_Model(ID: responseJson[0]['_id'],Name: responseJson[0]['NAME']);
      setState(() {
        this.companyData = responseJson;
      });
      return 'Success';
    } else {
      // If the response was umexpected, throw an error.
      throw Exception('Failed to load Bugs');
    }

  }

Initstate()上调用了getCompanies函数

  @override
          void initState() {
            this.getCompanies();
            super.initState();
          }

通过以下代码段动态创建下拉列表

DropdownButtonHideUnderline(
                        child: new DropdownButton(items: companyData.map((item){
                          return new DropdownMenuItem(
                              child: Text(
                                item['NAME']
                              ),
                            value: item['_id'].toString(),
                          );
                         }).toList(),
                          hint: Text(
                           ' selected item here ' // how get the seletced item
                        ),
                            isDense: true,
                        isExpanded: true,
                        onChanged: (String value){
                          onChangeCompany;
                          setState(() {
                            ticketForm.CompanyID=value;
                          });
                          print(value);
                        }),
                      )

0 个答案:

没有答案