Flutter 移动光标 关闭弹出的键盘

移动光标

要移动光标先要将目标view关联对应的FocusNode, 然后通过FocusScope来request对应的FocusNode即可。

关闭弹出的键盘

- 如果关联了对应的FocusNode, 直接调用focusNode.unfocus()即可
- 如果没有关联, 直接用 FocusScope.of(context).requestFocus(FocusNode()); 

完成案例如下:

class FocusTestRoute extends StatefulWidget {
  @override
  _FocusTestRouteState createState() => new _FocusTestRouteState();
}

class _FocusTestRouteState extends State {
  FocusNode focusNodeUserName = new FocusNode();
  FocusNode focusNodePassword = new FocusNode();
  FocusScopeNode focusScopeNode;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(16.0),
      child: Column(
        children: [
          TextField(
            autofocus: true,
            focusNode: focusNodeUserName,
            //关联focusNodeUserName
            decoration: InputDecoration(labelText: "用户名"),
            textInputAction: TextInputAction.next,
            // 设置键盘 "下一步" 按钮
            onSubmitted: (_) {
              // 点击键盘上的 "下一步" 回调
              focusNodeUserName.unfocus();
              FocusScope.of(context).requestFocus(focusNodePassword);
            },
          ),
          TextField(
            focusNode: focusNodePassword, //关联focusNodePassword
            decoration: InputDecoration(labelText: "密码"),
            textInputAction: TextInputAction.done, // 设置键盘 "完成" 按钮
            onSubmitted: (_) {
              // 点击键盘上的 "完成" 回调
              // 关闭弹出的键盘
              focusNodePassword.unfocus();
              // 如果没有关联focusnode 要关闭键盘可以用:  FocusScope.of(context).requestFocus(FocusNode());
            },
          ),
        ],
      ),
    );
  }
}

你可能感兴趣的:(flutter)