【问题标题】:Flutter: How to shift focus to next TextFormField?Flutter:如何将焦点转移到下一个 TextFormField?
【发布时间】:2021-02-25 19:43:34
【问题描述】:

我是 Flutter 的新手,我想在当前 TextFormField 达到其 maxLength 时从一个 TextFormField 移动到另一个,而无需按 Enter。这意味着我可以在小时 TextFormField 上输入 2 位数字,而焦点 TextFormField 将移动到分钟 TextFormField 等等。

我已经尝试过使用 nextFocus(),但这仅在按 enter 时有效。

小时输入小部件示例:

Widget _buildHH(){
    return Theme(
      data: Theme.of(context).copyWith(primaryColor: Colors.orange),
      child: Expanded(
        child:
        TextFormField(
          maxLength: 2,
          cursorColor: Colors.orange,
          style: TextStyle(color: Colors.orange),
          decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: 'HH'
          ),
          onEditingComplete: () => FocusScope.of(context).nextFocus(),
          keyboardType: TextInputType.number,
          validator: (String value){
            return null;
          },
          onSaved: (String value){
            _HH = value;
          },
        ),
      )
    );
  }


【问题讨论】:

    标签: flutter textformfield


    【解决方案1】:

    给你所有的TextFormFieldFocusNodeTextEditingController

      TextEditingController fooController = TextEditingController();
      TextEditingController bahController = TextEditingController();
    
      FocusNode fooFocusNode;
      FocusNode bahFocusNode;
    
     @override
      void initState() {
        super.initState();
    
        fooFocusNode = FocusNode();
        bahFocusNode = FocusNode();
      }
    
    @override
      void dispose() {
    
        fooFocusNode.dispose();
        bagFocusNode.dispose();
        fooController.dispose();
        bahController.dispose();
        super.dispose();
      }
    

    ControllerFocusNode 分配给您的TextFormField

    在您的TextFormField 中侦听onChanged,这将返回您的控制器拥有的当前值。 从这里你可以做一个简单的检查,看看你的参数是否满足。

    onChanged: (value) {
    
      if (value.length >= 2) {
        fooFocusNode.unfocus();
        FocusScope.of(context).requestFocus(bahFocusNode);
      }
    },
    

    【讨论】:

      【解决方案2】:
      final node = FocusScope.of(context);
      

      在构建方法下初始化这个变量

      onChanged: (value) {
                         if (value.length == 2) node.nextFocus();
                           },
      

      将此 onChanged 方法添加到您的 TextFormField, 如果 textfield 中的文本长度等于 2,它将自动转移焦点。

      【讨论】:

      • 完全按照需要工作,感谢您的快速回复。
      猜你喜欢
      • 2022-12-11
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2019-02-08
      • 2016-06-30
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      相关资源
      最近更新 更多