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

拜拜、爱过 提交于 2020-01-01 09:32:47

问题


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?


回答1:


maxLength property is available in Flutter

https://docs.flutter.io/flutter/material/TextField/maxLength.html

just add maxLength: 45, in properties of TextField




回答2:


Use inputFormatters property

example:

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

namespace

import 'package:flutter/services.dart';



回答3:


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

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



回答4:


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;
        } 
    }
);



回答5:


You can control everything about the Text Field with the TextEditingController. So if you were to pair this information with an onChanged event from the TextField you could perform any logic you like in there. For example:

TextEditingController _controller = new TextEditingController();
String text = ""; // empty string to carry what was there before it onChanged
int maxLength = ...
...
new TextField(
    controller: _controller,
    onChanged: (String newVal) {
        if(newVal.length <= maxLength){
            text = newVal;
        }else{
            _controller.text = text;
        }

    }
)

I am able to control the text field to stay within the guidelines because if it ever goes over it, it will revert to what it was before the last type.



来源:https://stackoverflow.com/questions/44955063/how-can-i-limit-the-size-of-a-text-field-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!