繁体   English   中英

DropdownButton 无法更新它的值(空)

[英]DropdownButton can't update it's value(null)

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

问题是,

第一:我无法更新我的 selectedCity,它没有得到更新。 此外,打印函数调用 null,因为我的 cityList 数据类似于 [new york, paris, london] 等...

第二:flutter 不会完全将焦点从任何 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 中添加这一行,如下所示:

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

到这里: onChanged:(){setSate((){here}}

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

我希望它会帮助你。 我稍微修改了你的代码

 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);
                  });
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM