flutter 如何限制TextFormField中的字符数?

ktca8awb  于 2023-03-13  发布在  Flutter
关注(0)|答案(5)|浏览(393)

dart语言中,有没有一种方法可以使TextFormField中的最大输入长度保持固定?

sshcrbum

sshcrbum1#

使用inputFormatters属性。以下代码将textFormField的长度限制为42:

new TextFormField(
  inputFormatters: [
    new LengthLimitingTextInputFormatter(42),
  ],
);

**更新:**首先导入程序包。import 'package:flutter/services.dart';

vulvrdjw

vulvrdjw2#

使用maxLength

TextFormField(
  controller: _deskripsiController,
  onFieldSubmitted: (String value){
        setState(() {
          _deskripsiController.text = value;
        });
  },
  decoration: const InputDecoration(
        border: const UnderlineInputBorder(),
        labelText: "Deskripsi",
  ),
  maxLength: 8,
)
2ic8powd

2ic8powd3#

最好的方法是inputFormatters选项:

inputFormatters: [
   new LengthLimitingTextInputFormatter(11),// for mobile 
],
dsekswqp

dsekswqp4#

除了hahnsaja应答之外,在你添加maxLength之后,counter会出现在TextFormField小部件的底部。为了能够隐藏它,把它添加到InputDecoration中:

counterText: '',
counterStyle: TextStyle(fontSize: 0),

示例:

TextFormField(
  controller: _deskripsiController,
  onFieldSubmitted: (String value){
        setState(() {
          _deskripsiController.text = value;
        });
  },
  decoration: const InputDecoration(
        border: const UnderlineInputBorder(),
        labelText: "Deskripsi",
        counterText: '',
        counterStyle: TextStyle(fontSize: 0),
  ),
  maxLength: 8,
)
jbose2ul

jbose2ul5#

尝试使用以下代码

TextFormField(inputFormatters: [LengthLimitingTextInputFormatter(10)])

相关问题