List<DropdownMenuItem<String>> department = [];
@override
void initState() {
super.initState();
department.add(DropdownMenuItem(
value: 'DEP0000001',
child: Text('IT - SAP'),
));
department.add(DropdownMenuItem(
value: 'DEP0000002',
child: Text('HR - Admin'),
));
department.add(DropdownMenuItem(
value: 'DEP0000003',
child: Text('Engineering'),
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
DropdownButton(
items: department,
onChanged: (value) {
setState(() {
_deptCode = value;
});
},
hint: Text('Select Department'),
value: _deptCode,
),
],
),
);
}
在这里,我可以获取部门代码的值。但是,我也想获得部门名称。我试图获取String数据文本小部件,但我认为这是不可能的。有什么办法吗?
答案 0 :(得分:1)
您可以维护地图,以后再使用它来获取数据。 例如:
var data = {
'DEP0000001':'IT - SAP',
'DEP0000002' : 'HR - Admin',
'DEP0000003' : 'Engineering'
};
...
void initState() {
super.initState();
department.add(DropdownMenuItem(
value: 'DEP0000001',
child: Text(data['DEP0000001']),
));
department.add(DropdownMenuItem(
value: 'DEP0000002',
child: Text(data['DEP0000002]),
));
department.add(DropdownMenuItem(
value: 'DEP0000003',
child: Text(data['DEP0000003']),
));
}
以后您可以使用
获取数据print("The department ${data[_deptCode]} has code of $_deptCode");
希望对您有所帮助:)
答案 1 :(得分:0)
class MyHomePageState extends State<MyHomePage> {
var list = [
{"name": "IT - SAP", "id": "DEP0000001"},
{"name": "HR - Admin", "id": "DEP0000002"},
{"name": "Engineering", "id": "DEP0000003"},
];
var _deptCode;
@override
void initState() {
_deptCode = list.first;
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
DropdownButton(
items: list
.map((f) => DropdownMenuItem(
value: f,
child: Text(f["name"]),
))
.toList(),
onChanged: (value) {
setState(() {
print(value["name"]);
_deptCode = value;
});
},
hint: Text('Select Department'),
value: _deptCode,
),
],
),
);
}
}
答案 2 :(得分:-1)
您也可以使用“item.child.data”而无需维护“Map”。
List<int> searchDropDownByValue(String keyword, items) {
List<int> ret = [];
if (keyword != null &&
items != null &&
keyword.isNotEmpty) {
keyword.split(" ").forEach((k) {
int i = 0;
items.forEach((item) {
if (k.isNotEmpty &&
(item.child.data
.toString()
.toLowerCase()
.contains(k.toLowerCase()))) {
ret.add(i);
}
i++;
});
});
}
if (keyword.isEmpty) {
ret =
Iterable<int>.generate(items.length).toList();
}
return (ret);
}