[英]How to pass a validator to the `TextFormField' in Flutter?
我在我的顫振應用程序中為我的表單動態生成文本字段。 請檢查以下代碼
Widget _buildInputFields(
String label,
TextEditingController textController,
TextInputType textInputType,
IconData icon,
Color iconColor,
) {
return Container(
margin: EdgeInsets.only(left: 20, bottom: 20),
child: Container(
padding: EdgeInsets.only(right: 20),
child: Row(
children: <Widget>[
Flexible(
child: TextFormField(
controller: textController,
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
},
style: new TextStyle(color: Colors.white),
keyboardType: textInputType,
decoration: InputDecoration(
labelText: label,
fillColor: Colors.white,
labelStyle: TextStyle(
color: Colors.white, fontWeight: FontWeight.w600),
enabledBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.white30, width: 2.0),
borderRadius: BorderRadius.circular(25.0),
),
suffixIcon: IconButton(
icon: Icon(icon, color: iconColor),
onPressed: () {},
)),
),
),
],
),
));
}
上面的方法返回一個TextFormField
和我需要的樣式,所以我不必重新編碼數百次。 我只是調用該方法,然后得到一個新的TextFormField
無論如何,我需要進行表單驗證,每個字段都有不同的驗證。在顫振中,如何將validator
傳遞給textformfield
?
您可以簡單地將驗證器作為參數傳遞,就像您對其他人所做的那樣。 您只需要傳入一個將字符串作為參數並返回字符串的函數。
//username validator possible structure
Function(String) usernameValidator = (String username){
if(username.isEmpty){
return 'Username empty';
}else if(username.length < 3){
return 'Username short';
}
return null;
};
//password validator possible structure
passwordValidator(String password){
if(password.isEmpty){
return 'Password empty';
}else if(password.length < 3){
return 'PasswordShort';
}
return null;
}
//new build function
Widget _buildInputFields(
String label,
TextEditingController textController,
TextInputType textInputType,
IconData icon,
Color iconColor,
String Function(String) validator
) {
return Container(
margin: EdgeInsets.only(left: 20, bottom: 20),
child: Container(
padding: EdgeInsets.only(right: 20),
child: Row(
children: <Widget>[
Flexible(
child: TextFormField(
controller: textController,
validator: validator,
style: new TextStyle(color: Colors.white),
keyboardType: textInputType,
decoration: InputDecoration(
labelText: label,
fillColor: Colors.white,
labelStyle: TextStyle(
color: Colors.white, fontWeight: FontWeight.w600),
enabledBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.white30, width: 2.0),
borderRadius: BorderRadius.circular(25.0),
),
suffixIcon: IconButton(
icon: Icon(icon, color: iconColor),
onPressed: () {},
)),
),
),
],
),
));
}
//calling your function
_buildInputFields(label, textController, textInputType, icon, iconColor, usernameValidator);
_buildInputFields(label, textController, textInputType, icon, iconColor, passwordValidator);
nonybrighto答案是完全正確的,但是在添加空檢查更新代碼之后是
// Function to create form field
Widget createFormField(String label, TextEditingController controller,
String? Function(String?)? validator) {
return TextFormField(
decoration: InputDecoration(labelText: label),
controller: controller,
autovalidate: true,
validator: validator,
);
}
// Validator
String? Function(String?)? idValidator = (String? value) {
if (value!.isEmpty) {
return 'Id Must be entered';
} else {
return int.tryParse(value) == null ? 'Id Must be number' : null;
}
};
// Finally
createFormField('Id', idController, idValidator),
由於您已經在使用驗證器,我想您只需將其作為參數傳遞給_buildInputFields
,對嗎?
它會是這樣的:
Widget _buildInputFields(
...
Color iconColor,
Function validator,
) {
...
child: TextFormField(
controller: textController,
validator: validator,
style: new TextStyle(color: Colors.white),
...
}
你可以使用它,你會很好的。
但是,您可以更具體並使用驗證器Function
類型,如下所示:
Widget _buildInputFields(
...
Color iconColor,
FormFieldValidator<String> validator,
...
因此,您可以將驗證器定義為State
類的方法並重用它們,或者直接在_buildInputFields
調用中指定它們。
在下面的示例中,您有一個字段 Name,它使用 _notEmptyValidator,這是在同一類中定義的一種方法。 由於 LastName 遵循相同的邏輯,因此它重用了此方法。
...
String _notEmptyValidator(String value) {
if (value.isEmpty) {
return 'Please enter some text';
}
}
...
Column(
children: <Widget>[
_buildInputFields("Name", _notEmptyValidator),
_buildInputFields("Last Name", _notEmptyValidator),
text" : null),
]
...
在下面的示例中,我保留了以前的字段,但我正在添加一個新字段。 這個新字段有一個非常具體的驗證邏輯,我將在_buildInputFields
調用中定義驗證方法,因此不會在其他字段中重用它。
...
Column(
children: <Widget>[
_buildInputFields("Name", _notEmptyValidator),
_buildInputFields("Last Name", _notEmptyValidator),
text" : null),
_buildInputFields("Valid Number", (value) {
if (double.tryParse(value) == null) {
return "Please input a valid number";
}
},
]
...
如果您需要向您的方法發送的不僅僅是值,您還可以在驗證器中創建一個內部函數。 為了在驗證器中實現內部化,我需要它。
TextFormField(
// The validator receives the text that the user has entered.
validator: (value) {
return myMethod(value, context, ...);
},
//... other attributes
)
對於顫振 2
Custom Widget Function
CupertinoTextFormFieldRow customTextField(
String pretext, String supportText, Function(String) validatorFun) {
return CupertinoTextFormFieldRow(
prefix: Text(pretext),
placeholder: supportText,
validator: (val) => validatorFun(val!),
);
}
Define validator functions
acceptNonNull(String value) {
if (value.trim().isEmpty) {
return 'Please enter a value';
}
return null;
}
checkPassword(String value) {
if (value.isEmpty) {
return 'Password empty';
} else if (value.length < 8) {
return 'Password too weak';
} //accept only if string contains both alphabests and numerics
else if (!value.contains(RegExp(r'^[a-zA-Z0-9]+$'))) {
return 'Password should contain aplpha numeric characters';
}
return null;
}
Build your Widgets
customTextField("First Name", "Enter Your First Name Here",acceptNonNull),
customTextField("Last Name", "Enter Your Last Name Here", acceptNonNull),
customTextField("Password", "Choose a Password", checkPassword)
只是一個簡單的例子,使用nullsafety,flutter 2,getx
登錄_屏幕
validator: (value) {
return AuthController.instance.emailValidator(AuthController.instance.emailController.text);
},
Auth_Controller
emailValidator(String email){
if ((!email.contains('@')) ||
(email.trim().length < 8))
{
return 'Invalid email';
}
//validado com sucesso
return null;
}
對於具有空安全性的新更新,您應該使用它,因為如果您使用經過驗證的答案,它會給您一個錯誤。
//username validator possible structure
Function(String?) usernameValidator = (String? username){
if(username!.isEmpty){
return 'Username empty';
}else if(username!.length < 3){
return 'Username short';
}
return null;
};
//password validator possible structure
passwordValidator(String? password){
if(password!.isEmpty){
return 'Password empty';
}else if(password!.length < 3){
return 'PasswordShort';
}
return null;
}
//new build function
Widget _buildInputFields(
String label,
TextEditingController textController,
TextInputType textInputType,
IconData icon,
Color iconColor,
String? Function(String?) validator
) {
return Container(
margin: EdgeInsets.only(left: 20, bottom: 20),
child: Container(
padding: EdgeInsets.only(right: 20),
child: Row(
children: <Widget>[
Flexible(
child: TextFormField(
controller: textController,
validator: validator,
style: new TextStyle(color: Colors.white),
keyboardType: textInputType,
decoration: InputDecoration(
labelText: label,
fillColor: Colors.white,
labelStyle: TextStyle(
color: Colors.white, fontWeight: FontWeight.w600),
enabledBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Colors.white30, width: 2.0),
borderRadius: BorderRadius.circular(25.0),
),
suffixIcon: IconButton(
icon: Icon(icon, color: iconColor),
onPressed: () {},
)),
),
),
],
),
));
}
//calling your function
_buildInputFields(label, textController, textInputType, icon, iconColor, usernameValidator);
_buildInputFields(label, textController, textInputType, icon, iconColor, passwordValidator);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.