【问题标题】:Textfield limit the number of lines using multiline keyboardType文本字段使用多行keyboardType限制行数
【发布时间】:2019-01-20 16:21:02
【问题描述】:

使用带有键盘类型的文本字段:TextInputType.multiline 不限制用户可以输入的最大行数。

new TextField(
    keyboardType: TextInputType.multiline,
    maxLines: 4,  
    maxLength: 30,
) 

通过这个例子,用户可以添加 30 个换行符,例如,有什么方法可以限制用户使用 TextField 属性输入的行数?

我可以稍后用我自己的方法解析文本,但我的问题是要查找是否有任何 TextField 属性可以帮助解决这个问题。

谢谢!

【问题讨论】:

    标签: flutter


    【解决方案1】:

    所以感觉是个问题。你可以找到它here

    maxLines 设置为一个值而不是null 以扩展的TextField 开头,行号等于maxLines 值,然后,您可以输入任意数量的行。

    因此,我建议您使用TextController

      final _myController = TextEditingController();
      var _textFieldCorrectValue = '';
    
      @override
      void initState() {
        // TODO: implement initState
        _myController.addListener(_chekNumberOfLines);
        super.initState();
      }
    
     @override
      void dispose() {
        // TODO: implement dispose
        _myController.dispose();
        super.dispose();
      }
    

    并在您的 TextField 上使用它

    TextField(
          keyboardType: TextInputType.multiline,
          maxLines: 4,
          maxLength: 30,
          controller: _myController,
        ),
    

    这里是检查功能:

    void _chekNumberOfLines() {
        var _lines = _myController.text.split('\n');
        if (_lines.length > 4) {
          _myController.text = _textFieldCorrectValue;
        } else {
          _textFieldCorrectValue = _myController.text;
          var cursorPos = _myController.selection;
          // https://github.com/flutter/flutter/issues/11416
          // workaround for cursor position
          cursorPos = new TextSelection.fromPosition(new TextPosition(offset: _myController.text.length));
          _myController.selection = cursorPos;
        }
      }
    

    cursor position 的解决方法有点棘手,因为您无法更改光标位置。但我的目标是向您展示这个问题和一个快速的答案。如果您喜欢它,请使用它或以其他方式评论它。如果您找到了更好的方法,当然可以毫不犹豫地改进我的代码!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      相关资源
      最近更新 更多