You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的TextField中添加不可删除的两位小数前缀0.00

固定不可删除0.00前缀的TextField实现方案

你当前使用的prefix属性仅为TextField外部的静态展示文本,不属于输入框内容本身,无法实现前缀和用户输入内容绑定、不可删除的需求。可以通过自定义输入格式化器+控制器初始化的方式实现,具体实现如下:

1. 自定义输入格式化器

class FixedPrefixFormatter extends TextInputFormatter {
  // 固定前缀
  final String fixedPrefix = '0.00';

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    // 强制输入内容始终以前缀开头,防止用户删除前缀
    if (!newValue.text.startsWith(fixedPrefix)) {
      return oldValue;
    }
    // 限制光标无法移动到前缀范围内,避免用户选中前缀修改
    if (newValue.selection.baseOffset < fixedPrefix.length) {
      return newValue.copyWith(
        selection: TextSelection.collapsed(offset: fixedPrefix.length),
      );
    }
    // 保留两位小数的输入限制,仅允许前缀后输入合法金额格式
    final userInput = newValue.text.substring(fixedPrefix.length);
    if (RegExp(r'^\d*\.?\d{0,2}$').hasMatch(userInput)) {
      return newValue;
    }
    return oldValue;
  }
}

2. 修改TextField配置

CupertinoFormRow(
  child: CupertinoTextFormFieldRow(
    controller: controller.price,
    onChanged: (value) {
      // 计算时提取用户实际输入的内容即可
      final inputPrice = value.length > 4 ? value.substring(4) : '';
      controller.calTotal(controller.qty.text, inputPrice);
    },
    placeholder: "Enter item price",
    // 初始化时默认填充前缀
    initialValue: '0.00',
    inputFormatters: [
      FixedPrefixFormatter(),
    ],
  ),
),

实现说明

  • 输入框初始化默认填充0.00前缀,用户进入页面时前缀默认存在
  • 格式化器会拦截所有输入操作,确保前缀不会被删除、修改,光标也无法移动到前缀区域
  • 保留了你需要的两位小数输入限制,用户仅可在前缀后输入合法的金额数字
  • 实际业务计算、提交时,通过substring(4)截取前缀后的内容即可拿到用户输入的实际金额

内容的提问来源于stack exchange,提问作者nesece

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 12:30:03