无法以编程方式将焦点设置到ExpansionTile内部的TextField中

问题描述 投票:1回答:1

我有一个带有ExpansionTileTextField,并在用户扩展图块时尝试将焦点设置为此文本字段。但是由于某些原因,我无法使其正常运行。这是代码:

ExpansionTile(
  key: PageStorageKey<String>("notes_key"),
  title: Text(
    "Notes",
    style: TextStyle(color: Colors.indigo),
  ),
  onExpansionChanged: (expanded){
    if(expanded){
      FocusScope.of(context).requestFocus(_notesFocusNode);
      _notesController.value = _notesController.value.copyWith(text: _notes);
    } else {
      _notesFocusNode.unfocus();
    }
  },
  children: <Widget>[
   Row(
     crossAxisAlignment: CrossAxisAlignment.center,
     children: <Widget>[
       Expanded(
         child: TextField(
           decoration: InputDecoration(
             border: InputBorder.none,
           ),
           textInputAction: TextInputAction.newline,
           style: TextStyle(color: Colors.black),
           keyboardType: TextInputType.multiline,
           focusNode: _notesFocusNode,
           controller: _notesController,
           key: PageStorageKey("notes_field_key"),
           minLines: 1,
           maxLines: null,
           onChanged: (value) => _notes = value,
         ),
       ),
       IconButton(
         icon: Icon(Icons.done),
         color: Colors.teal,
         onPressed: () => _notesFocusNode.unfocus(),
       ),
     ],
   ),
 ],
)

感谢任何帮助。

对于更大的上下文,该文本字段不在任何形式内。所提供的代码位于较大的代码内部,并包装在ListView中。我可能需要在父视图中有一些关注范围?

flutter
1个回答
0
投票

TextFormField尚无法在展开Focus时获得Tile。它仅在动画开始几毫秒后可用。由于您没有办法知道动画何时完成,因此可以通过添加延迟来解决。我建议最少使用200毫秒,这样动画就不会错开,但是TextFormField会聚焦:

Future.delayed(Duration(milliseconds: 200), (){
  FocusScope.of(context).requestFocus(_notesFocusNode);
});
© www.soinside.com 2019 - 2024. All rights reserved.