解决方案: flutter要求DropdownButton中的value值与List<String> items中的值有重合
换句话说,让你的value有一个固定的初始值,这里用图举例
附上官方代码(可以直接copy):
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
String dropdownValue = 'One';
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: dropdownValue,
icon: const Icon(Icons.arrow_downward),
elevation: 16,
style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String? newValue) {
setState(() {
dropdownValue = newValue!;
});
},
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
附上我的垃圾代码(仅供参考,与本人记录):
List<String> bookitem = ["Brand New", "Almost New", "Good","Acceptable"];
String dropdownValue = "Brand New";
Positioned(
top: HYSizeFit.setPx(300),
left: HYSizeFit.setPx(110),
child: DropdownButton(
icon: const Icon(Icons.arrow_downward),
elevation: 16,
items: bookitem
.map((e) => DropdownMenuItem(
child: Text(e),
value: e,
))
.toList(),
value: dropdownValue,
onChanged: (value) {
setState(() {
dropdownValue= value.toString();
});
},
),
)
参考链接:
1.https://api.flutter.dev/flutter/material/DropdownButton-class.html
2.https://www.youtube.com/watch?v=w2EwuiKsUqU
|