Flutter Dropdown的默认值

时间:2019-11-21 22:53:28

标签: flutter flutter-layout

我有一个充满模型的下拉列表

  List<PetKeyValue> _data = [
    PetKeyValue(key: 'Perrito', value: '1'),
    PetKeyValue(key: 'Gatito', value: '2'),
  ];


  DropdownButton<PetKeyValue>(
     hint: Text(_selectedType),
      isExpanded: true,
      items: _data.map((data) {
        return DropdownMenuItem<PetKeyValue>(
          value: data,
          child: Text(data.key),
        );
      }).toList(),
      onChanged: (PetKeyValue value) {
        _selectedType = value.key;
        setState(() {
        _selectedTypeId = value.value;
        });
      },
    ),
  ),

要填充的类模型很简单

class PetKeyValue {
   String key;
   String value;

   PetKeyValue({this.key, this.value});
}

一切正常,但我无法为我的下拉菜单选择默认值

使用

value:'text'我有错误,

value仅接受PetKeyValue()实例,但都不起作用

enter image description here

1 个答案:

答案 0 :(得分:1)

value分配给列表中的现有对象。示例:

List<PetKeyValue> _data = [
  PetKeyValue(key: 'Perrito', value: '1'),
  PetKeyValue(key: 'Gatito', value: '2'),
];

...

DropdownButton<PetKeyValue>(
  value: _data[0],
  hint: Text("Hello"),
  isExpanded: true,
  items: _data.map((data) {
    return DropdownMenuItem<PetKeyValue>(
             value: data,
             child: Text(data.key),
           );
  }).toList(),
  onChanged: (value) {
    log(value.value);
  },
),

value: PetKeyValue(key: 'Gatito', value: '2'),将失败,因为DropdownButton正在检查该值是否在列表中并且使用==运算符,而PetKeyValue(key: 'Gatito', value: '2') == PetKeyValue(key: 'Gatito', value: '2')实际上是 false