我有一个初始化的类FormGroup
:
final form = FormGroup(
{
'oldPassword': FormControl<String>(
value: null,
validators: [
Validators.required,
],
),
'newPassword': FormControl<String>(
value: null,
touched: true,
validators: [
Validators.pattern(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$',
validationMessage:
'Required: \n * One uppercase and one downcase letter \n * Atleast one number \n * Atleast 8 characters')
],
),
'repeatPassword': FormControl<String>(
value: null,
validators: [
Validators.required,
],
),
},
validators: [
Validators.mustMatch(
'newPassword',
'repeatPassword',
)
],
);
我创建了一个 StatefullWidget 类ReactivePasswordField
:
import 'package:flutter/material.dart';
import 'package:reactive_forms/reactive_forms.dart';
class ReactivePasswordField extends StatefulWidget {
final String controlName;
final String hintText;
final Function() onSubmitted;
const ReactivePasswordField({
required this.controlName,
required this.hintText,
required this.onSubmitted,
});
@override
_ReactivePasswordFieldState createState() => _ReactivePasswordFieldState();
}
class _ReactivePasswordFieldState extends State<ReactivePasswordField> {
bool isObscure = true;
IconData icon = Icons.visibility_off;
late String controlName;
@override
void initState() {
controlName = widget.controlName;
super.initState();
}
@override
Widget build(BuildContext context) {
return ReactiveTextField(
autofocus: true,
obscureText: isObscure,
formControlName: 'oldPassword',
onSubmitted: () => widget.onSubmitted,
validationMessages: (control) => {
'required': 'Field cannot be empty.',
'mustMatch': 'New password must match.'
},
decoration: InputDecoration(
filled: true,
prefixIcon: Icon(
Icons.lock,
color: Color(0xffe96cbd),
),
hintText: widget.hintText,
suffixIcon: GestureDetector(
onTap: () {
if (isObscure) {
setState(() {
icon = Icons.visibility_off;
isObscure = false;
});
} else {
setState(() {
icon = Icons.visibility;
isObscure = true;
});
}
},
child: Icon(
icon,
color: Color(0xff3A4A78),
)),
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(20.0),
),
),
);
}
}
我这样做了,因为我希望每个ReactivePasswordField
人都有自己的状态来管理显示和隐藏输入视图。问题是当我输入到ReactivePasswordField
其他一个有相同的输入时。我的验证器也不起作用。我该如何解决?
我ReactivePasswordFields
在初始化 FormGroup 的类中使用了我的方法:
SingleChildScrollView(
child: ReactiveForm(
formGroup: form,
child: Column(
children: [
ReactivePasswordField(
controlName: 'oldPassword',
hintText: 'Current password',
onSubmitted: () => form.focus('newPassword')),
Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: ReactivePasswordField(
controlName: 'newPassword',
hintText: 'New password',
onSubmitted: () => form.focus('repeatPassword'),
),
),
ReactivePasswordField(
controlName: 'repeatPassword',
hintText: 'Repeat password',
onSubmitted: () => {},
)
],
),
)),