我正在尝试列出用户可以添加到的项目。 为此,我决定使用ListView小部件,其中每一行都是一个TextFormField小部件。 我希望新添加的项目在绘制后立即获得焦点。
我遵循以下食谱: https://api.flutter.dev/flutter/widgets/Focus-class.html#widgets.Focus.3
其中有一条评论解释说,在构建之前调用.requestFocus()
应该没问题。
但是当我将ActionChip
小部件替换为TextFormField
小部件时,新项目不会不获得焦点。
这是我的代码:
class SettingsWidget extends StatefulWidget {
SettingsWidget(this.addIngredientsListener);
final StreamController<String> addIngredientsListener;
@override
SettingsWidgetState createState() => SettingsWidgetState();
}
class SettingsWidgetState extends State<SettingsWidget> {
final List<Widget> children = new List<Widget>();
final List<FocusNode> childFocusNodes = new List<FocusNode>();
@override
void initState() {
super.initState();
widget.addIngredientsListener.stream.listen(_addChild);
_addChild("init");
_addChild("init");
}
@override
void dispose() {
super.dispose();
childFocusNodes.forEach((node) => node.dispose());
}
void _addChild(String caller) {
setState(() {
String text = 'CHILD ${children.length}';
// Calling requestFocus here creates a deferred request for focus, since the
// node is not yet part of the focus tree.
FocusNode newNode = FocusNode(debugLabel: 'Child ${children.length}')..requestFocus();
childFocusNodes
.add(newNode);
TextEditingController textController = TextEditingController(
text: text);
children.add(
TextFormField(
autofocus: false,
focusNode: newNode,
controller: textController
));
newNode.requestFocus();
});
}
@override
Widget build(BuildContext context) {
Widget widget = ListView.separated(
padding: const EdgeInsets.all(16.0),
itemCount: children.length,
itemBuilder: (context, i) {
return children[i];
},
separatorBuilder: (BuildContext context, int index) => const Divider());
return widget;
}
}
我已经成功地手动请求将焦点集中在列表中已经存在的TextFormFields上。 因此,我认为必须要阻止新的对象获得关注。
我有一个解决方法,其中手动添加的TextFormField具有autofocus: true
,而由initState()
创建的TextFormField没有。令我感到困惑的是,手动要求将重点放在新项目上无法正常工作。
我还看到This question on S/O,其中线程等待几毫秒来调用requestFocus()
。它也对我有用。
真的没有比让线程休眠焦点调用更好的选择了吗?
版本:
[✓] Flutter (Channel stable, v1.12.13+hotfix.9, on Linux, locale en_GB.UTF-8)
• Flutter version 1.12.13+hotfix.9 at /opt/flutter
• Framework revision f139b11009 (5 months ago), 2020-03-30 13:57:30 -0700
• Engine revision af51afceb8
• Dart version 2.7.2
答案 0 :(得分:0)
首先确实有一些编译错误需要解决:
setState(() {
..requestFocus();
上删除多余的点然后,再次测试,看看一切是否开始正常工作。