如何防止输入后,一些长度在Flutter文本字段

sg2wtvxw  于 2023-05-19  发布在  Flutter
关注(0)|答案(2)|浏览(129)

如果项目数量为3,则用户必须输入3序列号(逗号分隔)。我想防止用户进一步键入,如果逗号分隔字符串长度达到3。此外退格也应该工作,如果他想删除一些值。请在此指导我:

下面是我的代码:

TextFormField(
                    cursorColor: titleTextColor,
                    decoration: const InputDecoration(
                      labelText: "Serial #",
                      labelStyle: TextStyle(color: appBarColor),
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: appBarColor),
                      ),
                      //[focusedBorder], displayed when [TextField, InputDecorator.isFocused] is true
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: appBarColor),
                      ),
                    ),
                    validator: (val) {
                      if (val!.isEmpty) {
                        return 'Required';
                      }
                    },
                    controller: serialsController,
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.done,
                    onChanged: (val) {
                      if (val.isNotEmpty) {
                        int len = val.split(",").length;
                        if (double.parse(len.toString()) > double.parse(itemListOrderDetail[index].LineQuantity.toString())) {
                          showToast("Stop", FToast().init(context));
                        }
                      }
                    },
                  )
ubbxdtey

ubbxdtey1#

在这种情况下,一个好的解决方案是使用面罩。检查此包easy mask https://pub.dev/packages/easy_mask
所以,当你改变qtd数u也改变掩码。
编辑。
你也可以使用onChanged prop来控制…

onChanged:(val){
     if(val.split(',').length > 3){
       yourController.text = val.substring(0,val.length-1);
     }
   } ,

通过您的QTD变量或控制器更改数字3

6uxekuva

6uxekuva2#

您可以使用名为inputFormatters的属性在flutter TextFormField上实现此功能。
您必须创建自己的类来扩展TextInputFormatter类。
例如:

class SerialNoFormatter extends TextInputFormatter {
  SerialNoFormatter({required this.quantity}) : super();

  final int quantity;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    if (newValue.text.split(',').length > quantity) {
      return oldValue;
    }
    return newValue;
  }
}

相关问题