我无法找到一种方法来创建一个输入字段颤振,将打开一个数字键盘,应该采取数字输入。这是可能的颤振材料部件?一些GitHub讨论似乎表明这是一个受支持的功能,但我无法找到任何关于它的文档。
设置键盘和验证器
String numberValidator(String value) {
if(value == null) {
return null;
}
final n = num.tryParse(value);
if(n == null) {
return '"$value" is not a valid number';
}
return null;
}
new TextFormField(
keyboardType: TextInputType.number,
validator: numberValidator,
textAlign: TextAlign.right
...
https://docs.flutter.io/flutter/material/TextFormField/TextFormField.html https://docs.flutter.io/flutter/services/TextInputType-class.html
你可以指定数字为keyboardType的TextField使用:
keyboardType: TextInputType.number
检查一下我的总管。飞镖文件
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return new MaterialApp(
home: new HomePage(),
theme: new ThemeData(primarySwatch: Colors.blue),
);
}
}
class HomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new HomePageState();
}
}
class HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.white,
body: new Container(
padding: const EdgeInsets.all(40.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new TextField(
decoration: new InputDecoration(labelText: "Enter your number"),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
),
],
)),
);
}
}
您可以使用keyboardType参数轻松更改输入类型 你有很多可能性检查文档TextInputType 所以你可以使用号码或电话值
new TextField(keyboardType: TextInputType.number)
你可以试试这个:
TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
prefixIcon: Text("Enter your number: ")
),
initialValue: "5",
onSaved: (input) => _value = num.tryParse(input),
),
对于那些正在寻找使TextField或TextFormField只接受数字作为输入的人,尝试以下代码块:
用于flutter 1.20或更新版本
TextFormField(
controller: _controller,
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
// for below version 2 use this
FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
// for version 2 and greater youcan also use this
FilteringTextInputFormatter.digitsOnly
],
decoration: InputDecoration(
labelText: "whatever you want",
hintText: "whatever you want",
icon: Icon(Icons.phone_iphone)
)
)
对于1.20的早期版本
TextFormField(
controller: _controller,
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter.digitsOnly
],
decoration: InputDecoration(
labelText:"whatever you want",
hintText: "whatever you want",
icon: Icon(Icons.phone_iphone)
)
)
对于那些需要在文本字段中使用货币格式的人:
只使用:,(逗号)和。(期)
并阻止符号:-(连字符,减号或破折号)
以及:⌴(空格)
在你的TextField,只需设置以下代码:
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [BlacklistingTextInputFormatter(new RegExp('[\\-|\\ ]'))],
符号连字符和空格仍然会出现在键盘上,但会被阻塞。
keyboardType: TextInputType。number会在焦点上打开一个num pad,当用户输入/经过任何其他内容时,我将清除文本字段。
keyboardType: TextInputType.number,
onChanged: (String newVal) {
if(!isNumber(newVal)) {
editingController.clear();
}
}
// Function to validate the number
bool isNumber(String value) {
if(value == null) {
return true;
}
final n = num.tryParse(value);
return n!= null;
}
下面是Android上实际的手机键盘代码:
按键部分:keyboardType: TextInputType.phone,
TextFormField(
style: TextStyle(
fontSize: 24
),
controller: _phoneNumberController,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
prefixText: "+1 ",
labelText: 'Phone number'),
validator: (String value) {
if (value.isEmpty) {
return 'Phone number (+x xxx-xxx-xxxx)';
}
return null;
},
),
通过这个选项,你可以严格限制另一个字符的数字。
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
keyboardType: TextInputType.number,
使用上述选项,您必须导入此
import 'package:flutter/services.dart';
使用这种选项,用户不能在文本框中粘贴字符
您可以将这两个属性与TextFormField一起使用
TextFormField(
keyboardType: TextInputType.number
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
它只允许输入数字,没有其他的东西。
https://api.flutter.dev/flutter/services/TextInputFormatter-class.html
下面是数字键盘的代码: keyboardType: TextInputType。当你在文本框中添加这个代码时,它将打开数字键盘。
final _mobileFocus = new FocusNode();
final _mobile = TextEditingController();
TextFormField(
controller: _mobile,
focusNode: _mobileFocus,
maxLength: 10,
keyboardType: TextInputType.phone,
decoration: new InputDecoration(
counterText: "",
counterStyle: TextStyle(fontSize: 0),
hintText: "Mobile",
border: InputBorder.none,
hintStyle: TextStyle(
color: Colors.black,
fontSize: 15.0.
),
),
style: new TextStyle(
color: Colors.black,
fontSize: 15.0,
),
);
对于数字输入或数字键盘,您可以使用keyboardType: TextInputType.number
TextFormField(
decoration: InputDecoration(labelText:'Amount'),
controller: TextEditingController(
),
validator: (value) {
if (value.isEmpty) {
return 'Enter Amount';
}
},
keyboardType: TextInputType.number
)
如果需要使用双位数:
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),],
onChanged: (value) => doubleVar = double.parse(value),
RegExp('[0-9.,]')允许0到9之间的数字,也允许逗号和点。
double.parse()将字符串转换为double。
别忘了你需要: 导入的包:颤振/ services.dart ';
U可以安装intl_phone_number_input包
dependencies:
intl_phone_number_input: ^0.5.2+2
试试下面的代码:
import 'package:flutter/material.dart';
import 'package:intl_phone_number_input/intl_phone_number_input.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var darkTheme = ThemeData.dark().copyWith(primaryColor: Colors.blue);
return MaterialApp(
title: 'Demo',
themeMode: ThemeMode.dark,
darkTheme: darkTheme,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(title: Text('Demo')),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
final TextEditingController controller = TextEditingController();
String initialCountry = 'NG';
PhoneNumber number = PhoneNumber(isoCode: 'NG');
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InternationalPhoneNumberInput(
onInputChanged: (PhoneNumber number) {
print(number.phoneNumber);
},
onInputValidated: (bool value) {
print(value);
},
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
backgroundColor: Colors.black,
),
ignoreBlank: false,
autoValidateMode: AutovalidateMode.disabled,
selectorTextStyle: TextStyle(color: Colors.black),
initialValue: number,
textFieldController: controller,
inputBorder: OutlineInputBorder(),
),
RaisedButton(
onPressed: () {
formKey.currentState.validate();
},
child: Text('Validate'),
),
RaisedButton(
onPressed: () {
getPhoneNumber('+15417543010');
},
child: Text('Update'),
),
],
),
),
);
}
void getPhoneNumber(String phoneNumber) async {
PhoneNumber number =
await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber, 'US');
setState(() {
this.number = number;
});
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
}
TextField小部件需要设置keyboardType: 和inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter。digitsOnly]只接受数字作为输入。
TextField(
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
),
在DartPad中的例子
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
theme: ThemeData(primarySwatch: Colors.blue),
);
}
}
class HomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return HomePageState();
}
}
class HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Container(
padding: const EdgeInsets.all(40.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("This Input accepts Numbers only"),
SizedBox(height: 20),
TextField(
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.greenAccent, width: 5.0),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red, width: 5.0),
),
hintText: 'Mobile Number',
),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
),
SizedBox(height: 20),
Text("You can test be Typing"),
],
)),
);
}
}
正如接受的答案所述,指定keyboardType会触发一个数字键盘:
keyboardType: TextInputType.number
其他好的回答指出,一个简单的基于正则表达式的格式化器可以用来只允许输入整数:
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
],
这样做的问题是正则表达式一次只匹配一个符号,因此限制小数点的数量(例如)不能通过这种方式实现。
另外,其他人也表明,如果一个人想验证一个十进制数,它可以通过使用TextFormField和它的验证器参数来实现:
new TextFormField(
keyboardType: TextInputType.number,
validator: (v) => num.tryParse(v) == null ? "invalid number" : null,
...
这样做的问题是,它不能交互式地实现,而只能在表单提交时实现。
我希望只允许输入十进制数字,而不是稍后验证。我的解决方案是编写一个自定义格式化器利用int.tryParse:
/// Allows only decimal numbers to be input.
class DecimalNumberFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
// Allow empty input and delegate formatting decision to `num.tryParse`.
return newValue.text != '' && num.tryParse(newValue.text) == null
? oldValue
: newValue;
}
}
另外,也可以为自定义格式化器使用regex,这将应用于整个输入,而不仅仅是单个符号:
/// Allows only decimal numbers to be input. Limits decimal plates to 3.
class DecimalNumberFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
// Allow empty input.
if (newValue.text == '') return newValue;
// Regex: can start with zero or more digits, maybe followed by a decimal
// point, followed by zero, one, two, or three digits.
return RegExp('^\\d*\\.?\\d?\\d?\\d?\$').hasMatch(newValue.text)
? newValue
: oldValue;
}
}
这样,我还可以将小数板的数量限制为3。
你可以添加键盘类型的输入格式,就像这样
TextField(
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],// Only numbers can be entered
keyboardType: TextInputType.number,
);
这里是关于如何添加数字键盘,如何进行验证,如何添加样式,以及dart/flutter中的其他内容的所有细节。 我希望它能帮助你更好地学习。
Padding(
padding: const EdgeInsets.all(3.0),
child: TextFormField(
maxLength: 10,
keyboardType: TextInputType.number,
validator: (value) {
if (value.isEmpty) {
return 'Enter Number Please';
}
return null;
},
decoration: InputDecoration(
prefixIcon: Icon(Icons.smartphone),
prefixText: '+92',
labelText: 'Enter Phone Number',
contentPadding: EdgeInsets.zero,
enabledBorder: OutlineInputBorder(),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 2, color: Theme
.of(context)
.primaryColor,
)
),
focusColor: Theme
.of(context)
.primaryColor,
),
),
),
我需要en IntegerFormField与最小/最大的控制。最大的问题是当焦点改变时,oneditingcomplete没有被调用。以下是我的解决方案:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vs_dart/vs_dart.dart';
class IntegerFormField extends StatefulWidget {
final int value, min, max;
final InputDecoration decoration;
final ValueChanged<TextEditingController> onEditingComplete;
IntegerFormField({@required this.value, InputDecoration decoration, onEditingComplete, int min, int max})
: min = min ?? 0,
max = max ?? maxIntValue,
onEditingComplete = onEditingComplete ?? ((_) {}),
decoration = decoration ?? InputDecoration()
;
@override
_State createState() => _State();
}
class _State extends State<IntegerFormField> {
final TextEditingController controller = TextEditingController();
@override
void initState() {
super.initState();
controller.text = widget.value.toString();
}
@override
void dispose() {
super.dispose();
}
void onEditingComplete() {
{
try {
if (int.parse(controller.text) < widget.min)
controller.text = widget.min.toString();
else if (int.parse(controller.text) > widget.max)
controller.text = widget.max.toString();
else
FocusScope.of(context).unfocus();
} catch (e) {
controller.text = widget.value.toString();
}
widget.onEditingComplete(controller);
}
}
@override
Widget build(BuildContext context) {
return Focus(
child: TextFormField(
controller: controller,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
keyboardType: TextInputType.number,
decoration: widget.decoration,
),
onFocusChange: (value) {
if (value)
controller.selection = TextSelection(baseOffset: 0, extentOffset: controller.value.text.length);
else
onEditingComplete();
},
);
}
}
仅限号码类型
keyboardType: TextInputType.number
和更多的选择与数字垫
keyboardType: TextInputType.numberWithOptions(decimal: true,signed: false)
为避免粘贴的不是数字值,添加后
keyboardType: TextInputType.number
这段代码:
inputFormatters: [FilteringTextInputFormatter.digitsOnly]
从https://api.flutter.dev/flutter/services/FilteringTextInputFormatter-class.html
设置你的keyboardType为TextInputType.number,
例如:keyboardType: TextInputType.number,
TextFormField(
controller: yourcontroller,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: 'Mobile',
suffixIcon: Padding(
padding: EdgeInsets.only(),
child:
Icon(Icons.phone_outlined, color: Color(0xffff4876)),
),
),
validator: (text) {
if (text == null || text.isEmpty) {
return 'Please enter your Mobile No.';
}
return null;
},
),
TextField(
controller: _controller,
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp(r'[0.0-9.9]')),
])
以下是Flutter中实际手机键盘的代码:
//Mobile
const TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
prefixIcon: Icon(Icons.phone), hintText: 'Mobile'),
),
只需将此添加到您的TextFormField
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp(r'[0-9]')), ],
的例子,
TextFormField(
controller: textController,
onChanged: (value) {
print(value);
},
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
],
),
你需要加一条线
keyboardType: TextInputType.phone,
在块“TextFormField”。在下面的例子:
TextField(
controller: _controller,
keyboardType: TextInputType.phone,
),
它应该是这样的:
推荐文章
- 检测输入是否有文本在它使用CSS -在一个页面上,我正在访问和不控制?
- 如何用jQuery清空输入字段
- 在Flutter中向有状态小部件传递数据
- 未处理异常:ServicesBinding.defaultBinaryMessenger在绑定初始化之前被访问
- 出现键盘时,Flutter小部件将调整大小。如何预防这种情况?
- 使用Javascript函数设置输入值
- <input type='button' />和<input type='submit' />之间的差异
- 颤振-换行文本
- CSS输入宽度:100%超出父边界
- 如何在Dart中四舍五入到小数点后的给定精度程度?
- 添加一个启动屏幕颤振应用程序
- 如何将输入读取为数字?
- 在flutter中等同于wrap_content和match_parent ?
- 多行文本字段在扑动
- 如何在颤振文本下划线