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

如何在Flutter中创建仅支持数字输入的输入框?

如何用Flutter Material组件实现仅接受数字输入并唤起数字键盘的输入框

当然可以通过Flutter的Material组件实现这个需求!官方其实早就支持该特性了,只是需要把几个配置项组合起来用,我给你整理了两种常用的实现方式:

基础版:仅允许输入整数

这种方式会直接唤起纯数字键盘,同时限制用户只能输入数字字符:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

// 在你的Widget中使用
TextField(
  // 指定唤起数字键盘
  keyboardType: TextInputType.number,
  // 过滤所有非数字输入
  inputFormatters: <TextInputFormatter>[
    FilteringTextInputFormatter.digitsOnly,
  ],
  decoration: const InputDecoration(
    labelText: '请输入数字',
    border: OutlineInputBorder(),
  ),
)

这里keyboardType: TextInputType.number负责让系统唤起数字键盘,FilteringTextInputFormatter.digitsOnly会拦截所有非数字的输入内容,双重保障实现仅数字输入的效果。

进阶版:支持小数或负数输入

如果你的场景需要输入金额、温度这类带小数或负数的数字,可以调整配置:

TextField(
  // 唤起带小数点/负号选项的数字键盘
  keyboardType: TextInputType.numberWithOptions(decimal: true, signed: true),
  // 自定义正则过滤,允许数字、开头的负号和一个小数点
  inputFormatters: <TextInputFormatter>[
    FilteringTextInputFormatter.allow(RegExp(r'^-?\d+\.?\d*')),
  ],
  decoration: const InputDecoration(
    labelText: '请输入数字(支持小数/负数)',
    border: OutlineInputBorder(),
  ),
)

这个配置会唤起适配小数和负数输入的数字键盘,同时通过正则表达式限制输入格式,避免出现多个小数点、中间插入负号这类非法输入。

你提到在GitHub看到这是支持特性但没找到文档,其实这些配置都在TextField的官方API文档里,只是需要把keyboardType和inputFormatters两个参数结合使用,单独查看某一个参数可能不容易联想到组合后的效果哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:13:18