flutter 如何从TextEditingController(TextFormField)中删除前导零

xzlaal3s  于 2023-05-08  发布在  Flutter
关注(0)|答案(2)|浏览(155)

我有一个带控制器的TextFormField。在这个控制器中,初始值为0,但用户可以增加或减少该数字。这就是代码:

TextFormField(
                controller: _controller,
                keyboardType: TextInputType.number,
                textAlign: TextAlign.center,
                onChanged: (value) {
                  _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();
  }

例如,TextFormField的初始值是0,如果我输入3,它会保留第一个零:

// How it is now
// Initial State:
// 0
// I put a three:
// 03

//How I want:
// Initial State:
// 0
// I put a three:
// 3

我怎么够得着这个?

w1e3prcc

w1e3prcc1#

onChanged:(value){
if (value[0] =="0") controller.text = value.substring(1);
}
ulydmbyx

ulydmbyx2#

onChanged: (val){
          if(val.characters.characterAt(0) == Characters("0") && val.length > 1){
            // we need to remove the first char
            textEditingController.text = val.substring(1);
            // we need to move the cursor
            textEditingController.selection = TextSelection.collapsed(offset: textEditingController.text.length);
          }
        },

相关问题