如何解决我的 textFormField 在左侧插入新值,如何仅在右侧插入
我有一个只接受数字(最多 4 个)的 TextFormField。这个值是用户想要的物品数量,所以,第一个状态是 0,在用户输入第一个值后它会更新,但我不想显示第一个零(初始状态是 0,用户输入 1,我只想显示数字 1 而不是零)所以我添加了这个代码:
if (value.isNotEmpty && value != null && value[0] =="0") _controller.text = value.substring(1);
这是文本字段:
TextFormField(
controller: _controller,keyboardType: TextInputType.number,textAlign: TextAlign.center,onChanged: (value) {
// this is what i added
if (value.isNotEmpty && value != null && value[0] =="0") _controller.text = value.substring(1);
// some methods I take out cause is irrelevant
_setQuantity();
setState(() {
quantidade = int.tryParse(_controller.text);
});
},inputFormatters: [
FilteringTextInputFormatter.digitsOnly,LengthLimitingTextInputFormatter(4),],style: TextStyle(
color: Colors.white,fontSize: 22.0,),cursorColor: AppColorSecondary,decoration: InputDecoration(
filled: true,fillColor:
Colors.white,border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),borderSide: BorderSide(color: Colors.transparent),
控制器:
void _setQuantity() {
Provider.of<Product>(context,listen: false).setQuantity(
int.tryParse(_controller.text));
}
@override
void initState() {
_controller = TextEditingController(text: getSize().toString());
_controller.addListener(_setQuantity);
quantity = widget.size.quantity;
super.initState();
}
所以,在我添加了隐藏前导 0 的行后,后面键入的数字会插入右侧。例如:
// Initial state:
// 0
// Typed 3:
// 3
// Typed 2: (How is now)
// 23
// Typed 2: (HOW I WANT)
// 32
我该怎么做才能达到我的目标并在不显示前导零的情况下在右侧插入数字(如果后面还有其他数字)?
解决方法
在initState
中:
_controller = TextEditingController(text: getSize().toString() != '0' ? getSize().toString() : null);
在小部件中:
if(_controller.text.isEmpty) _controller.text = '0';
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。