TextField本身就可以添加一些限制条件.keyboardType: TextInputType.number,这样就只有数字和小数点了,但是在安卓里,有一些奇奇怪怪的键盘,所以我们就需要做一些判断和限制.
添加限制条件
keyboardType: TextInputType.number,
inputFormatters: [
// FilteringTextInputFormatter.digitsOnly,//数字,只能是整数
LengthLimitingTextInputFormatter(15), //限制长度
FilteringTextInputFormatter.allow(RegExp("[0-9.]")),//数字包括小数
//FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]")),//只允许输入字母
],
限制位数,但是每次从新赋值的时候,光标都会跑到第一位去,这时候我们就需要手动把光标放到最后.priceCon.selection = TextSelection.fromPosition(TextPosition(offset: priceCon.text.length));
这个就是移动光标的方法.也可以写在TextEditingController
里.
onChanged: (value) {
if (value.contains(".")) {
var vv = value.split('.');
if (vv.length > 2) {
priceCon.text = '${vv[0]}.${vv[1]}';
} else if (vv.length == 2) {
if (vv[1].length > 4) {
priceCon.text = moneyDoubleOrInt(
double.parse(priceCon.text),
postion: 4);
}
}
priceCon.selection =
TextSelection.fromPosition(TextPosition(
offset: priceCon.text.length));
}
},
全部代码
TextField(
controller: priceCon,
style: TextStyle(
color: getBlackColor(),
fontSize: SAdapt.size(15),
fontWeight: FontWeight.bold,
fontFamily: getSegoeUISemibold(),
),
keyboardType:
const TextInputType.numberWithOptions(
decimal: true),
onEditingComplete: () {
///点击发送调用
},
onChanged: (value) {
if (value.contains(".")) {
var vv = value.split('.');
if (vv.length > 2) {
priceCon.text = '${vv[0]}.${vv[1]}';
} else if (vv.length == 2) {
if (vv[1].length > 4) {
priceCon.text = moneyDoubleOrInt(
double.parse(priceCon.text),
postion: 4);
}
}
priceCon.selection =
TextSelection.fromPosition(TextPosition(
offset: priceCon.text.length));
}
},
decoration: InputDecoration(
hintText: 'Price'.tr,
hintStyle: TextStyle(
color: get999999Color(),
fontSize: SAdapt.size(15),
fontWeight: FontWeight.w400,
fontFamily: getSegoeUISemibold(),
),
isDense: true,
contentPadding: EdgeInsets.only(
left: SAdapt.width(17.5),
top: 5,
bottom: 5,
right: 10),
border: const OutlineInputBorder(
gapPadding: 0,
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
),
inputFormatters: [
LengthLimitingTextInputFormatter(15), //限制长度
FilteringTextInputFormatter.allow(
RegExp("[0-9.]")),
],
// minLines: 1,
),
网友评论