我想在我的 DropDownButton
中添加的对象:
class Car {
int id;
String make;
Car(this.id, this.make);
static List<Car> getCars() {
var cars = new List<Car>();
cars.add(Car(1, "Ford"));
cars.add(Car(2, "Toyota"));
cars.add(Car(3, "BMW"));
return cars;
}
}
构建 DropDown(StatefulWidget 状态类):
class _MyHomePageState extends State<MyHomePage> {
Car _selectedCar;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(child: getDropDown()));
}
Widget getDropDown() {
var cars = Car.getCars();
this._selectedCar = cars.first; // Default to first value in list.
var items = cars.map((car) {
return new DropdownMenuItem<Car>(
value: car,
child: new Text(car.make),
);
}).toList();
return DropdownButton<Car>(
value: this._selectedCar,
onChanged: (Car car) {
setState(() {
this._selectedCar = car;
});
},
items: items);
}
}
DropDownButton
在选择第一个项目时正确显示,但是当我选择另一个项目时,UI 永远不会更新以显示新项目被选中。
最佳答案
您只需要初始化列表一次,因为如果您在每次绘制时都初始化新列表,则不会匹配 DropDownList 值。
在这里找到工作示例:Gist
关于dart - DropDownButton 所选项目在 UI 中未更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55376400/