簡體   English   中英

Flutter 中的下拉按鈕不會將值更改為所選值

[英]DropdownButton in Flutter not changing values to the selected value

在我的代碼中,我添加了一個下拉列表,如下所示,當我在下拉列表中切換選擇時,它沒有更新它的顯示異常,我在 statefull 小部件中聲明了一個變量,在我的下拉列表 function 中,我將其作為 A 值分配給下拉列表按鈕,在 Onchanged 中我將 json 傳遞給另一個 function 我從變量中獲取值並將其分配給 setState 內的 opSelected 變量

class _ReportFilterState extends State<ReportFilter> {

  String opSelected;
 //declared string to hold the selected value in dropdown within the state class.

    buildMainDropdown(List<Map<String, Object>> items, StateSetter setState) {
        return Container(
          child: Padding(
            padding: const EdgeInsets.symmetric(
              horizontal: 27.0,
              vertical: 16.0,
            ),
            child: Align(
              alignment: Alignment.topLeft,
              child: DropdownButtonHideUnderline(
                child: DropdownButton(
                  isExpanded: true,
                  hint: Text("Choose Filters"),
                  value: opSelected, // Here assigning the value 
                  items: items
                      .map((json) => DropdownMenuItem(
                          child: Text(json["displayName"]), value: json))
                      .toList(),
                  onChanged: (json) {
                    manageIntState(json, setState);
                  },
                ),
              ),
            ),
          ),
        );
      }

 void manageIntState(Map<String, Object> jsonSelected, StateSetter setState) {
    setState(() {
      dispName = jsonSelected["displayName"]; 

//here I am setting the selected value
      opSelected = dispName;

//Doing some operations
      id = jsonSelected['id'];
      type = jsonSelected['type'];
      selectedFilterOption = jsonSelected;

      if (jsonSelected.containsKey("data")) {
        List<Map<String, Object>> tempList;
        List<String> dailogContent = List<String>();
        tempList = jsonSelected['data'];

        tempList
            .map((val) => {
                  dailogContent.add(val['displayId']),
                })
            .toList();
        _showReportDialog(dailogContent);
      }
    });
  }

但是當我運行時,我最終會出錯

項目==空|| items.isEmpty||value==null||itsems.where((DropdownMenuItem item)=>item.value==value).length==1 不正確..

讓我知道我在代碼中做錯了什么,所以如果我評論它沒有顯示選定的下拉值,它就會像這樣給我。

DropdownButton的選定value不是其項目的值之一時,就會發生該錯誤。

在您的情況下,您的項目值是json ,它是Map<String, Object> ,並且DropdownButton的值是opSelected ,它是String

所以你需要像這樣改變opSelected的類型:

Map<String, Object> opSelected;

還要確保您將相同項目列表的引用傳遞給buildMainDropdown() ,因為如果您在調用buildMainDropdown()時創建一個新列表,那么DropdownButton將有另一個選項引用並且這是不允許的


注意:您可能希望對 Map 使用動態而不是 Object,如下所示:

Map<String, dynamic> opSelected;

這是為什么: dart中的動態和Object有什么區別?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM