Home > Mobile >  I wanna limit value of a quantity that user put on the text field (Flutter)
I wanna limit value of a quantity that user put on the text field (Flutter)

Time:12-13

I want a user can input no more than 100 in my textfield. If a user put more than 100 --let's say 123--, the text will show 100 instead of 123.

here is my code

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

CodePudding user response:

You can use the onChanged callback to listen to the changes

    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),
    )

CodePudding user response:

The simplest approach is to supply an onChanged() callback to a TextField or a TextFormField. Whenever the text changes, the callback is invoked.

A more powerful, but more elaborate approach, is to supply a TextEditingController as the controller property of the TextField or a TextFormField.

Details on here:https://docs.flutter.dev/cookbook/forms/text-field-changes

CodePudding user response:

You can use the maxLength property to set the maximum characters allowed in the TextField. Read more about it here.

  • Related