我无法找到在Flutter中创建可打开数字键盘的输入字段的方法。这可能与Flutter材料小部件一起使用吗?一些github讨论似乎表明这是一个受支持的功能,但我无法找到任何有关它的文档。
答案 0 :(得分:59)
您可以使用以下内容为keyboardType指定号码TextField:
keyboardType: TextInputType.number
检查我的main.dart文件
import 'package:flutter/material.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,
),
],
)),
);
}
}
答案 1 :(得分:12)
设置键盘和验证器
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
...
答案 2 :(得分:8)
对于那些希望使TextField或TextFormField接受的人仅接受数字。试试这个代码块。
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))
)
答案 3 :(得分:7)
通过此选项,您可以严格限制没有编号的其他字符。
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
keyboardType: TextInputType.number,
要使用上述选项,您必须导入此
import 'package:flutter/services.dart';
使用这种选项的用户无法将char粘贴到文本字段中
答案 4 :(得分:6)
您可以将这两个属性与TextFormField一起使用
TextFormField(
keyboardType: TextInputType.number
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
只允许输入数字,没有其他内容。
https://api.flutter.dev/flutter/services/TextInputFormatter-class.html
答案 5 :(得分:5)
需要 TextField
小部件来设置 keyboardType: TextInputType.number,
和 inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter.digitsOnly]
只接受数字作为输入。
TextField(
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
], // Only numbers can be entered
),
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"),
],
)),
);
}
}
答案 6 :(得分:3)
对于那些需要在文本字段中使用 money格式的人:
仅使用:,(逗号)和。 (句号)
并阻止符号:-(连字符,减号或破折号)
以及⌴(空白)
在您的TextField中,只需设置以下代码:
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [BlacklistingTextInputFormatter(new RegExp('[\\-|\\ ]'))],
simbols连字符和空格仍将出现在键盘中,但会被阻止。
答案 7 :(得分:2)
您可以使用keyboardType参数轻松更改输入类型 并且您有很多可能性检查文档TextInputType 所以你可以使用号码或电话价值
new TextField(keyboardType: TextInputType.number)
答案 8 :(得分:1)
keyboardType: TextInputType.number
将打开一个数字键盘,当用户输入/粘贴其他任何内容时,我将清除文本字段。
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;
}
答案 9 :(得分:1)
如果您需要使用双号:
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),],
onChanged: (value) => doubleVar = double.parse(value),
RegExp('[0-9.,]')
允许使用0到9之间的数字,也可以使用逗号和点。
double.parse()
从字符串转换为双精度。
别忘了您需要:
import 'package:flutter/services.dart';
答案 10 :(得分:1)
如接受的答案所述,指定 keyboardType
会触发数字键盘:
keyboardType: TextInputType.number
其他好的答案指出,一个简单的基于正则表达式的格式化程序可用于只允许输入整数:
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9]')),
],
这样做的问题是正则表达式一次只匹配一个符号,因此无法通过这种方式限制小数点的数量(例如)。
此外,其他人还表明,如果想要验证十进制数,可以通过使用 TextFormField
和它的 validator
参数来实现:
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;
}
}
或者,可以对自定义格式化程序使用正则表达式,这将应用于整个输入,而不仅仅是单个符号:
/// 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 个。
答案 11 :(得分:0)
您可以尝试以下方法:
TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
prefixIcon: Text("Enter your number: ")
),
initialValue: "5",
onSaved: (input) => _value = num.tryParse(input),
),
答案 12 :(得分:0)
这是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;
},
),
答案 13 :(得分:0)
这是数字键盘的代码: keyboardType:TextInputType.phone 。在文本字段中添加此代码后,它将打开数字键盘。
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,
),
);
答案 14 :(得分:0)
对于数字输入或数字键盘,您可以使用keyboardType:TextInputType.number
TextFormField(
decoration: InputDecoration(labelText:'Amount'),
controller: TextEditingController(
),
validator: (value) {
if (value.isEmpty) {
return 'Enter Amount';
}
},
keyboardType: TextInputType.number
)
答案 15 :(得分:0)
您可以使用Form Builder Package显示任何类型的表单字段。对于数字输入字段,
FormBuilderTextField(
keyboardType: TextInputType.number,
validators: [
FormBuilderValidators.numeric(),
],
),
答案 16 :(得分:0)
你可以安装包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();
}
}