Flutter:如何在TextField上使用focusNode属性

rjzwgtxy  于 2022-12-05  发布在  Flutter
关注(0)|答案(3)|浏览(167)

我想在用户点击TextField widget时控制它。如何实现focusNode属性?描述中没有详细说明。

db2dz4w8

db2dz4w81#

FocusNode focusNode;

void initState() {
  focusNode = new FocusNode();

  // listen to focus changes
  focusNode.addListener(() => print('focusNode updated: hasFocus: ${focusNode.hasFocus}')); 
}

void setFocus() {
  FocusScope.of(context).requestFocus(focusNode);
}

Widget build() {
  return
  ...
  new TextField(focusNode: focusNode, ...);
}
ibrsph3r

ibrsph3r2#

不要忘记在以后处理它以避免内存泄漏:

@override
  void dispose() {
    focusNode.dispose();
    super.dispose();
  }
umuewwlo

umuewwlo3#

如何从外部进行对焦控制

FocusNode emailFocus = FocusNode();
FocusNode passFocus = FocusNode();

//添加GestureDetector获取外部触摸事件;

GestureDetector(
  onTap: () {
    try {
      emailFocus.unfocus();
      passFocus.unfocus();
    } catch (e) {
      print(e);
    }

    print("Tapped");
  },

//在文本字段中添加焦点

TextFormField(
                    autofocus: true,
                    focusNode: passFocus,

相关问题