Flutter 文本字段前缀文本问题

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

无法将前缀文本与输入文本对齐?

Padding(
              padding: const EdgeInsets.only(top: 40),
              child: TextField(
                controller: amountController,
                maxLines: 1,
                textAlign: TextAlign.end,
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.digitsOnly,
                  LengthLimitingTextInputFormatter(25),
                ],
                style:
                    const TextStyle(color: AppColors.textColor, fontSize: 14),
                decoration: const InputDecoration(
                  isDense: true,
                  prefixText: "\$",
                  prefixIconConstraints:
                      BoxConstraints(minWidth: 0, minHeight: 0),
                  labelText: AppStrings.transferAmount,
                  floatingLabelStyle: TextStyle(color: AppColors.textColor),
                  floatingLabelBehavior: FloatingLabelBehavior.always,
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: AppColors.primary,
                    ),
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: AppColors.borderColor,
                    ),
                  ),
                ),
                onChanged: (value) {
                  value = "\u0024 $value";
                },
              ),
            ),

尝试设置重力,但它没有与输入文本对齐

flutter textfield
1个回答
0
投票

如果您想将文本放在前缀后面,您需要更改

textAlign: TextAlign.end,
textAlign: TextAlign.start,

如果您只想在输入文本前添加 $ 符号,请使用此

onChange

onChanged: (value) {
          if (value.startsWith("\$")) {
            // if the string already starts with $, just use it as is
            amountController.text = value;
          } else {
            //If the string doesn't start with $, add it
            amountController.text = "\$" + value;
          }
          //Set the cursor at the end of the text
          amountController.selection = TextSelection.fromPosition(
            TextPosition(offset: amountController.text.length),
          );
        },

onChanged 函数不会直接修改 TextField 的值。它仅提供当前文本。在代码中,您将新值分配给某个值,但这不会影响 TextField。要更改 TextField 的文本,您应该使用 TextEditingController。

示例:

// In your TextField
TextField(
  controller: controller,
  onChanged: (value) {
    controller.text = "\u0024 $value";
    controller.selection = TextSelection.fromPosition(
        TextPosition(offset: controller.text.length),
      );
  },
)
© www.soinside.com 2019 - 2024. All rights reserved.