1.引入头文件
import 'package:flutter/services.dart';
2.
限制TextField 的输入长度需要inputFormatters 的属性及属性值:LengthLimitingTextInputFormatter(6)
代码如下
TextField(
style: TextStyle(fontSize: ScreenUtil().setWidth(16), color: Colors.black),
controller: _controller,//控制器
decoration: InputDecoration(
hintText: '请输入标题',
hintStyle: TextStyle( fontWeight: FontWeight.w500, fontSize: ScreenUtil().setWidth(20), color: Colors.grey[400]),
border: InputBorder.none,
),
inputFormatters: <TextInputFormatter>[
LengthLimitingTextInputFormatter(6)//限制长度
],
onChanged: (v){
// textField输入内容的回调
},
)),
这篇博客介绍了如何在Flutter中使用TextField组件限制用户输入的字符长度。通过设置inputFormatters属性为LengthLimitingTextInputFormatter(6),可以确保用户最多只能输入6个字符。这在创建标题或者短字段时非常有用。
4797

被折叠的 条评论
为什么被折叠?



