Search code examples
textfieldflutter

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


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?


Solution

  • I had to add an additional snippet to what RSproute mentioned. The full code is here:

    TextEditingController _controller = new TextEditingController();
    String text = ""; // empty string to carry what was there before it 
    onChanged
    int maxLength = ...
    ...
    new TextField(
        controller: _controller,
        onChange: (String newVal) {
            if(newVal.length <= maxLength){
                text = newVal;
            }else{
                _controller.value = new TextEditingValue(
                    text: text,
                    selection: new TextSelection(
                        baseOffset: maxLength,
                        extentOffset: maxLength,
                        affinity: TextAffinity.downstream,
                        isDirectional: false
                    ),
                    composing: new TextRange(
                        start: 0, end: maxLength
                    )
                );
                _controller.text = text;
            } 
        }
    );