在Flutter中一箇中文是一個長度,這裏我們將長度限制在20字,可以按照下面這種方式做:
TextField(
style: TextStyle(fontSize: ScreenUtil().setWidth(16), color: Colors.black),
controller: _cpyCode,//控制器
decoration: InputDecoration(
hintText: '請輸入標題',
hintStyle: TextStyle( fontWeight: FontWeight.w600, fontSize: ScreenUtil().setWidth(40), color: Colors.grey[400]),
border: InputBorder.none,
),
inputFormatters: <TextInputFormatter>[
LengthLimitingTextInputFormatter(20)//限制長度
],
onChanged: _listenCpyCode,
)),
其中LengthLimitingTextInputFormatter(20)
這個就是限制TextField長度,當長度大於20的時候就不會再輸入了。
覺得有用的話,可以點個贊。