首页 > 解决方案 > 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 永远不会更新以显示新项目为选中状态。

标签: dartflutterdropdownbutton

解决方案


您只需初始化一次列表,因为如果您在每次绘制时都初始化新列表,则 DropDownList 值不会匹配。

在这里找到的工作示例:Gist


推荐阅读