【问题标题】:My textFormField inserts new values at left, how to insert only at right我的 textFormField 在左侧插入新值,如何仅在右侧插入
【发布时间】:2021-07-27 20:59:49
【问题描述】:

我有一个 TextFormField,它只接受数字(最多 4 个)。这个值是用户想要的物品的数量,所以,第一个状态是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

我可以做些什么来达到我的目标并在右侧插入数字而不显示前导零(如果后面还有其他数字)?

【问题讨论】:

    标签: string flutter dart textfield


    【解决方案1】:

    initState:

    _controller = TextEditingController(text: getSize().toString() != '0' ? getSize().toString() : null);
    

    在小部件中:

    if(_controller.text.isEmpty) _controller.text = '0';
    

    【讨论】:

    • 我不认为它解决了 ltr textdirection 问题?
    猜你喜欢
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2015-06-27
    • 1970-01-01
    相关资源
    最近更新 更多