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

Flutter应用中如何校验TextFormField输入的内容是否为有效价格数值

Flutter 价格输入框校验实现方案

核心改动说明

  • 限制输入键盘类型为数字键盘,从输入源头减少无效内容
  • 增加输入过滤器,强制只允许输入符合要求的字符
  • 增加validator校验逻辑,提交时自动检查输入有效性,给出对应错误提示
  • 优化数值解析逻辑,避免非法输入导致的应用崩溃
// 顶部需要先导入输入格式化器依赖
import 'package:flutter/services.dart';

// 修改后的完整组件代码
Container(
  width: 150.0,
  child: TextFormField(
    initialValue: widget.update ? order.price.toString() : null,
    autocorrect: false,
    // 限制弹出数字键盘
    keyboardType: TextInputType.number,
    // 输入过滤器:只允许输入数字
    inputFormatters: [
      FilteringTextInputFormatter.digitsOnly,
    ],
    // 校验逻辑
    validator: (value) {
      if (value == null || value.isEmpty) {
        return '请输入商品价格';
      }
      final priceNum = int.tryParse(value);
      if (priceNum == null) {
        return '请输入有效数字';
      }
      if (priceNum <= 0) {
        return '价格不能小于等于0';
      }
      return null;
    },
    onSaved: (String value) {
      // 用tryParse替代parse避免异常,前面校验过这里不会为默认值0
      price = int.tryParse(value) ?? 0;
    },
    decoration: InputDecoration(
      labelText: "Price",
      hintText: 'Price',
      prefixText: "Rs.",
    ),
  ),
)

如果你需要支持带小数的价格,只需做两处修改:

  1. 键盘类型改为keyboardType: const TextInputType.numberWithOptions(decimal: true)
  2. 输入过滤器替换为FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}$')),可以限制最多保留2位小数,同时把代码里int相关的解析逻辑替换为double即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:24:03