我正在开发一个需要输入价格的应用程序,¥因此没有小数位.如果我们使用,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)
Hez*_*Hez 19
2021 年 4 月或之后的更新:
\nTextField(\n inputformatter: [\n FilteringTextInputFormatter.digitsOnly,\n ],\n textInputType: TextInputType.number,\nRun Code Online (Sandbox Code Playgroud)\n使用输入格式化程序的其他示例包括:
\nTextField(\n inputFormatters: [\n FilteringTextInputFormatter.deny(RegExp(r'[/\\\\]')),\n ],\n)\nRun Code Online (Sandbox Code Playgroud)\n或者
\ninputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'^ ?\\d*')),]\n inputFormatters: [FilteringTextInputFormatter.deny(' ')]\nRun Code Online (Sandbox Code Playgroud)\n或者
\nOther 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)\nRun Code Online (Sandbox Code Playgroud)\n所以在上面的情况下你可以有
\ninputFormatters: [\n WhitelistingTextInputFormatter(RegExp("[a-z A-Z \xc3\xa1-\xc3\xba \xc3\x81-\xc3\x9a 0-9]"))\n ]\nRun 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';
| 归档时间: |
|
| 查看次数: |
6123 次 |
| 最近记录: |