如何限制Flutter中文本字段的大小? [英] How can I limit the size of a text field in flutter?

查看:64
本文介绍了如何限制Flutter中文本字段的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TextField小部件似乎没有"limit"属性来限制可以键入的字符数.我如何强制只能在TextField小部件中提供一定数量的字符作为输入.我尝试查看装饰属性,并可能以某种方式设置限制,但这似乎也不起作用.我应该使用其他部件吗?

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?

推荐答案

我必须在RSproute提到的内容中添加一个附加代码段.完整的代码在这里:

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

这篇关于如何限制Flutter中文本字段的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆