Flutter / Android-将焦点从TextField移动到DropdownButton

atr*_*eon 5 flutter

我在屏幕上有一个文本字段和一个下拉按钮。当我从文本字段中移走以选择一个项目然后返回到文本字段时,我发现这有点尴尬。

  1. 在文字栏位中输入
  2. 通过点击两次来选择下拉菜单

我的问题是您必须轻按两次,一次退出文本字段,第二次访问下拉菜单-是否有一种方法可以退出文本字段并一键打开下拉列表?这是内置于Android还是Flutter控件?

这是一些浮动代码,显示下拉列表和文本框...

class _TextAndDropdownState extends State<TextAndDropdown> {
  int selectedDropdown;
  String selectedText;
  final textController = new TextEditingController();

  @override
  void initState() {
    super.initState();

    selectedDropdown = 1;

    textController.addListener(() => print(''));
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Text and dropdown'),
      ),
      body: Container(
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.all(10.0),
            ),
            DropdownButton(value: selectedDropdown, onChanged: _dropdownChange, items: [
              DropdownMenuItem(
                child: Text('First'),
                value: 1,
              ),
              DropdownMenuItem(child: Text('Seconds')),
            ]),
            TextField(controller: textController),
          ],
        ),
      ),
    );
  }

  void _dropdownChange(val) {
    setState(() {
      selectedDropdown = val;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

Sol*_*f93 27

抱歉迟到的答案......我也在为此找到解决方案。现在我懂了。

只有你必须添加这个

 FocusScope.of(context).requestFocus(new FocusNode());
Run Code Online (Sandbox Code Playgroud)

在你的

_dropdownChange(val) 方法

void _dropdownChange(val) {
                      FocusScope.of(context).requestFocus(new FocusNode());///It will clear all focus of the textfield
            setState(() {
              selectedDropdown = val;
                     });
                           }
Run Code Online (Sandbox Code Playgroud)

也参考阿卜杜勒·瓦哈卜的回答