数量输入,如Flutter中的PayPal

问题描述 投票:0回答:1

如何创建一个TextField来格式化PayPal中的金额,以便输入的数字被添加到右侧并向左移动?

例如,按1应显示0,01而不是1。其次是2应该导致0,12。当删除时,它应该在另一个方向做同样的事情,以便0,12成为0,01

paypal dart flutter textfield text-formatting
1个回答
0
投票

试试这个代码。它不太可读,但有效:

TextField(
              keyboardType: TextInputType.number,
              controller: controller,
              onChanged: (str){
                String newVal;
                if(lastState.length<str.length){
                  String newChar = str.substring(str.length-1).trim();
                  int valueToAdd = int.parse(newChar);
                  int current = int.parse(lastState.replaceAll(r",", ""));
                  newVal = (current*10+valueToAdd).toString();
                } else
                if(lastState.length>str.length){
                  int currentValue = int.parse(lastState.replaceAll(r",", ""));
                  newVal = (currentValue ~/ 10).toString();
                }
                if(newVal.length<3){
                  int x = 3-newVal.length;
                  for(int i=0;i<x;i++){
                    newVal = "0$newVal";
                  }
                }
                lastState = newVal.replaceRange(newVal.length-2, newVal.length, ",${newVal.substring(newVal.length-2)}");
                setState(() {
                  controller.text = lastState;
                });
              },
            ),

在你的班级扩展State添加:

String lastState = "0,00";
TextEditingController controller;

在你的initState()方法里面加上这一行:

controller = new TextEditingController(text: "0,00");
© www.soinside.com 2019 - 2024. All rights reserved.