dart - DropDownButton 所选项目在 UI 中没有改变
问题描述
我要添加的对象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
推荐阅读
- api - Swiftui 无法读取数据,因为它的格式不正确
- sql-server - BizTalk 中不理解操作轮询
- gcc - GDB 无法为 x86-64 可执行文件设置断点
- python - 如何根据另一个图像透明区域获取子图像(裁剪)
- java - 将输入文件中的数据读入类方法
- python - 从缺少 setup.py 文件的 git 存储库导入库
- php - Laravel 8 - 将验证错误传递回前端
- google-apps-script - 如何为所有填写的单元格重复功能(谷歌表格)
- java - 尝试连接到 android 上的 mongodb 数据库时出错
- javascript - 循环枚举radioButton中的对象