skip to Main Content

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

3

Answers


  1. You can use the onChanged callback to listen to the changes

        TextField(
          controller: qtyController,
          keyboardType: TextInputType.number,
          onTap: () => qtyController.text = '',
          onChanged: (val){
           if (val.isNotEmpty) {
            if(int.parse(val)>=100) {
              qtyController.text = "100";
            }
           }
          },
          inputFormatters: [
            FilteringTextInputFormatter.digitsOnly,
            LengthLimitingTextInputFormatter(3),
          ],
          textAlign: TextAlign.center,
          style: TextStyle(color: Colors.white),
        )
    
    Login or Signup to reply.
  2. You can use the maxLength property to set the maximum characters allowed in the TextField. Read more about it here.

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search