在Flutter中仅数字TextFormField

Eoi*_*oin 13 dart flutter

我正在开发一个需要输入价格的应用程序,¥因此没有小数位.如果我们使用,keyboardType: TextInputType.numberWithOptions()我们可以得到一个数字键盘输入.如果我们使用,validator: (input) { }我们可以检查输入是否有效,但我们无法阻止它.

问题是我们可以保存不需要验证的草稿.因此,我们最好只允许数字输入.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Digits Only',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextFormField(
              autovalidate: true,
              keyboardType: TextInputType.number,
              validator: (input) {
                final isDigitsOnly = int.tryParse(input);
                return isDigitsOnly == null
                    ? 'Input needs to be digits only'
                    : null;
              },
            ),
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法阻止某些文本输入,只允许数字?

die*_*per 29

是的,您可以使用该inputFormatters属性并添加WhitelistingTextInputFormatter.digitsOnly表达式

  import 'package:flutter/services.dart';


  TextFormField(
          ...
          inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
        )
Run Code Online (Sandbox Code Playgroud)

  • 哦,抱歉,我发现了这个``keyboardType: TextInputType.number,```` (4认同)

Hez*_*Hez 19

2021 年 4 月或之后的更新:

\n
TextField(\n   inputformatter: [\n      FilteringTextInputFormatter.digitsOnly,\n      ],\n   textInputType: TextInputType.number,\n
Run Code Online (Sandbox Code Playgroud)\n

使用输入格式化程序的其他示例包括:

\n
TextField(\n  inputFormatters: [\n    FilteringTextInputFormatter.deny(RegExp(r'[/\\\\]')),\n  ],\n)\n
Run Code Online (Sandbox Code Playgroud)\n

或者

\n
inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^ ?\\d*')),]\n   inputFormatters: [FilteringTextInputFormatter.deny(' ')]\n
Run Code Online (Sandbox Code Playgroud)\n

或者

\n
Other options include:\n\n> lowercase letters: a-z\n> capital letters: A-Z\n> lowercase vowels accented: \xc3\xa1-\xc3\xba\n> capital vowels accented: \xc3\x81-\xc3\x9a\n> numbers: 0-9\n> space : (space)\n
Run Code Online (Sandbox Code Playgroud)\n

所以在上面的情况下你可以有

\n
inputFormatters: [\n        WhitelistingTextInputFormatter(RegExp("[a-z A-Z \xc3\xa1-\xc3\xba \xc3\x81-\xc3\x9a 0-9]"))\n      ]\n
Run Code Online (Sandbox Code Playgroud)\n


Pau*_*elo 17

随着WhitelistingTextInputFormatter弃用,使用数:

keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[0-9.,]+')),],
onChanged: (value) => doubleVar = double.parse(value),
Run Code Online (Sandbox Code Playgroud)

RegExp('[0-9.,]+') 允许 0 到 9 之间的数字,还有逗号和点。

您可以使用RegExp('([0-9]+(\.[0-9]+)?)')允许数字和只有一个点。请参阅此处的说明。

double.parse() 从字符串转换为双精度。

不要忘记你需要: import 'package:flutter/services.dart';

  • RegExp('([0-9]+(\.[0-9]+)?)') 似乎不起作用。这有效:RegExp(r'(^\d*\.?\d*)') 请参阅此处:/sf/ask/4285041071/ (2认同)