【问题标题】:I wanna limit value of a quantity that user put on the text field (Flutter)我想限制用户放在文本字段上的数量的值(颤振)
【发布时间】:2022-01-16 15:20:44
【问题描述】:

我希望用户在我的文本字段中输入的内容不超过 100。 如果用户输入的数字超过 100——比如说 123——,文本将显示 100 而不是 123。

这是我的代码

TextField(
                                  controller: qtyController,
                                  keyboardType: TextInputType.number,
                                  onTap: () => qtyController.text = '',
                                  inputFormatters: [FilteringTextInputFormatter. digitsOnly,
                                    LengthLimitingTextInputFormatter(3),
                                  ],
                                  textAlign: TextAlign.center,
                                  style: TextStyle(color: Colors.white),
                                )

【问题讨论】:

    标签: flutter android-studio dart


    【解决方案1】:

    最简单的方法是向 TextField 或 TextFormField 提供 onChanged() 回调。每当文本更改时,都会调用回调。

    更强大但更复杂的方法是提供 TextEditingController 作为 TextField 或 TextFormField 的控制器属性。

    详情在此:https://docs.flutter.dev/cookbook/forms/text-field-changes

    【讨论】:

      【解决方案2】:

      您可以使用maxLength 属性来设置TextField 中允许的最大字符数。阅读更多关于它的信息here

      【讨论】:

        【解决方案3】:

        您可以使用onChanged 回调来监听更改

            TextField(
              controller: qtyController,
              keyboardType: TextInputType.number,
              onTap: () => qtyController.text = '',
              onChanged: (val){
                if(int.parse(val)>=100) {
                  qtyController.text = "100";
                }
              },
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(3),
              ],
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white),
            )
        

        【讨论】:

        • 谢谢。它解决了值限制问题,但是当我输入 123 时,它变为 100,然后我无法编辑数字。号码无法删除。它停留在 100。我该如何解决这个问题?
        • 希望你可以使用退格键
        • 代码在 dartpad 上运行良好
        • 是的,伙计。我使用退格键。但它不会成功。但无论如何,这不是一个大问题。非常感谢。
        猜你喜欢
        • 2020-04-30
        • 1970-01-01
        • 1970-01-01
        • 2018-09-21
        • 2017-11-13
        • 2020-11-24
        • 2022-01-14
        • 2021-07-15
        • 2022-01-17
        相关资源
        最近更新 更多