DropdownButton无法更新其值(空)

时间:2019-02-07 11:29:33

标签: dart flutter

整页代码很长,但是我的DropdownButton小部件代码是这样的。

问题是

第一:我无法更新我的selectedCity,它没有更新。另外,由于我的cityList数据类似于[纽约,巴黎,伦敦]等,因此打印功能调用null,

秒:颤动不会将焦点从任何TextField完全更改为DropdownButton。我的意思是,单击了TextField,然后单击了DropdownButton,但是单击按钮后,焦点恢复为该TextField。这是Flutter的默认动作吗?

  List<dynamic> _cityList;
  String _selectedCity;

  @override
  Widget build(BuildContext context) {
    return DropdownButton(
      value: _selectedCity,
      style: TextStyle(
        fontSize: 11,
        color: textColor,
      ),
      items: _cityList.map((city) {
        return DropdownMenuItem<String>(
          child: Padding(
            padding: const EdgeInsets.only(left: 4),
            child: Text(city),
          ),
        );
      }).toList(),
      onChanged: (String value) {
        setState(() {
          _selectedCity = value;
          print(_selectedCity);
        });
      },
      isExpanded: true,
    );
  }

编辑:从DropdownMenuItem中选择一个项目后重置FocusNode的解决方案是在setstate内添加此行,如下所示:

this:FocusScope.of(context).requestFocus(new FocusNode());

到此处:onChanged:(){setSate((){here}}}

2 个答案:

答案 0 :(得分:0)

对于焦点问题,您应该使用focusNodes,其中一个用于下拉列表,另一个用于文本字段https://docs.flutter.io/flutter/widgets/FocusNode-class.html

答案 1 :(得分:0)

我希望它将对您有所帮助。我对您的代码做了一些修改

 List<dynamic> _cityList;
 String _selectedCity;

它将显示下拉菜单按钮,当您单击该按钮并选择打印中显示的任何值

 @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      body: ListView(
        children: [
          Column(
            children: <Widget>[
              DropdownButton<String>(
                items: _cityList.map((dynamic value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                onChanged: (value) {
                  setState(() {
                    _selectedCity = value;
                    print(_selectedCity);
                  });
                },
              ),
            ],
          ),
        ],
      ),
    );
  }