How can I limit the size of a text field in flutter?

Viewed 100404

The TextField widget doesn't seem to have a "limit" attribute to limit the number of characters that can be typed. How I can enforce that only a certain number of characters can be provided as input in a TextField Widget. I tried looking at the decoration property and potentially setting the limit there somehow but that didn't seem to work either. Is there a different widget I should be using?

9 Answers

Use inputFormatters property

example:

TextFormField(
      inputFormatters: [
        LengthLimitingTextInputFormatter(10),
      ]
    )

namespace

import 'package:flutter/services.dart';

You can use the maxLength property and you can still hide the bottom counter text by setting the counterText to empty string.

TextField(
  maxLength: 10,
  decoration: InputDecoration(
    counterText: ''
  ),
)

With th version 1.25 this is even easier. The maxLengthEnforced property needs to be set to true. Otherwise the response above will not work.

     Container(
                  margin: EdgeInsets.only(right: 5),
                  child: SizedBox(
                    width: 70,
                    child: TextField(
                      keyboardType: TextInputType.number,
                      maxLengthEnforced: true,
                      maxLength: 2,
                      decoration: InputDecoration(
                        labelText: 'Hours',
                        counterText: '',
                      ),
                      controller: hourField,
                    ),
                  ),
                ),

enter image description here

You can set LengthLimitingTextInputFormatter in input formatters

TextField(
   keyboardType: TextInputType.number,
   inputFormatters: [
     FilteringTextInputFormatter.digitsOnly,
     LengthLimitingTextInputFormatter(n,), //n is maximum number of characters you want in textfield
   ],
),

You can use this code snipped to limit length and hide counter:

TextFormField(
   maxLength: 10,
   buildCounter: (BuildContext context, { int currentLength, int maxLength, bool isFocused }) => null,
);

Original answer you can find here.

There are two ways to do that

Solution One

LengthLimitingTextInputFormatter Creates a formatter that prevents the insertion of more characters than a limit.

      TextField(              
              inputFormatters: [
                new LengthLimitingTextInputFormatter(5), /// here char limit is 5
              ],
                ///....
              )

Solution Two:

          TextField(
                  maxLength: 5, /// here char limit is 5

If you don't want to show counter text at TextField bottom then add empty counterText in InputDecoration

Example:

TextField(
              maxLength: 100,
              decoration: InputDecoration(
                  counterText: '',
                  ///....
Related