【问题标题】:DropdownButton value is not updating after selecting values from DropdownItems. How to update default value with selectedLocation?从 DropdownItems 中选择值后,DropdownButton 值未更新。如何使用 selectedLocation 更新默认值?
【发布时间】:2021-10-31 01:15:58
【问题描述】:

从 DropdownItems 中选择值后,DropdownButton 值未更新。如何使用 _selectedLocation 更新默认值?
我使用的变量:

  String? stateToCountry;
  List? stateID;
  List? cityJson;
  Position? _position;
  String? currentAddress;
  Placemark? place;
    DropdownButton(
               hint:_selectedLocation==null ? Text('Dropdown') : Text(
                 _selectedLocation.toString(),
                 style: TextStyle(color: Colors.black),
               ),
              isExpanded: true,
              iconSize: 30,
              elevation: 16,
              underline: Container(
                height: 2,
                color: Colors.deepPurpleAccent,
              ),
              style: TextStyle(color: Colors.deepPurple, fontSize: 20.0),
              itemHeight: 50,
              items: countrylist!.map((location){
                return DropdownMenuItem(
                  value: location,
                  child: new Text(location["name"].toString()),

                );
              }).toList(),
              onChanged: (newValue){
                 setState(() {
                   _selectedLocation=newValue as String?;
                 });
              },

                ),

【问题讨论】:

标签: flutter dart


【解决方案1】:

下拉按钮的作用如下:

T 代表一个泛型类型,所以你可以传递 bool、String、double、YourCustomModel 等。

Dropdownbutton 需要 3 个东西:

  • T
  • 带有选项的List<T>
  • onChanged 函数,它将您选择的 T 值传递给您。

widget,知道选择哪个值作为他的实例, 每个对象都有一个hashCode 属性,可将其与其他对象区别开来, 当您选择一个选项时,您必须保留该实例。

例如,该实例应该在您的列表中

final list=<String>[
'Hello', /// hashCode 1
'good bye', /// hashCode 2
'bye bye' /// hashCode 3
];

当你选择一个时,这是通过onChanged,假设你选择了第一个选项:

onChanged:(value){
print(value.hashCode); /// output value: 1
// you must keep that instance with the same type `T`
_selectedValue=value;
}

所以现在,您的_selectedValue 将是:

print(_selectedValue.hashCode);/// /// output value: 1
print(_selectedValue); /// output value: 'Hello'

【讨论】:

    【解决方案2】:

    需要设置value属性,

    DropdownButton(
      value: _selectedLocation,
      onChanged:(newValue){
          setState(() {
            _selectedLocation=newValue;
          });
      }
    

    【讨论】:

    • 问题依旧。
    • 不要把它写成字符串?
    • 当我删除 'as String' 我得到另一个错误。
    猜你喜欢
    • 2019-05-31
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    相关资源
    最近更新 更多