问题
I need use a string as a value in the flutter dropdown. But returns
Another exception was thrown: 'package:flutter/src/material/dropdown.dart': Failed assertion: line 609 pos 15: 'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.
Full log here.
The code is
items: dataMaker.map((item) {
return new DropdownMenuItem<String>(
child: new Text(item['fabricante'],
textAlign: TextAlign.center),
value: item['fabricante'], //FAIL
);
}).toList(),
So my question in: How can i use a string as item value? Another solution is get the text of dropdown but i don´t know how.
--SOLUTION--
With this code I can find all the elements in the dataMaker list that have the same text as the drop-down menu.
var test =dataMaker.firstWhere((fabricante) => fabricante["id"].toString() == dropdownSelectionMaker);
dataModelo = dataMaker.where((modelo) => modelo["fabricante"] == test["fabricante"]).toList();
回答1:
You can try this method, Thats how i use sometimes.
Code may contain some problem bcz i have created it in normal TextEditor.
items: (){
List<Widget> data = List<Widget>();
for(int i=0;i<dataMaker.length;i++){
data.add(
DropdownMenuItem<String>(
child: Text(item['fabricante'],
textAlign: TextAlign.center),
value: item['fabricante'],
);
);
}
return data;
}
回答2:
try this hope its works for you :
new DropdownButton(
value: _current,
items: dataMaker.map((item) {
return new DropdownMenuItem<String>(
child: new Text(item.fabricante,
textAlign: TextAlign.center),
value: item.fabricante, //FAIL
);
}).toList(),
onChanged: (selected) => setState(() {
_current = selected;
});
回答3:
I'm not sure how the library does the comparison but I found that though the value was in he list it still returned the error, so I had to do some manula comparison.
Here's the magical line for my case:
value: selectedType == null ? selectedType : buildingTypes.where( (i) => i.name == selectedType.name).first as BuildingType,
return DropdownButton<T>(
hint: Text("Select Building type"),
value: selectedType == null ? selectedType : buildingTypes.where( (i) => i.name == selectedType.name).first as BuildingType,
onChanged: handleBuildingTypeChange,
items: abcList.map((T value) {
return DropdownMenuItem<T>(
value: value,
child: Row(
children: <Widget>[
SizedBox(
width: 10,
),
Text(
value.name,
style: TextStyle(color: Colors.black),
),
],
),
);
}).toList(),
);
来源:https://stackoverflow.com/questions/56111840/flutter-dropdown-value