Ben*_*ins 7 dart flutter flutter-reactive-forms
我在 Flutter 中使用reactive_forms,这是一个模型驱动的表单库,其灵感来自 Angular Reactive Forms。
添加一个带有一个名为“nickName”的 formControl 的表单非常简单:
final _form = FormGroup({
'nickName':
FormControl<String>(validators: [Validators.required]),
});
Run Code Online (Sandbox Code Playgroud)
我的问题是,将表单控件“nickName”绑定到域模型的属性不是常见的做法和良好的做法吗?因为这是我在 Angular 中开发的另一个代码库中所做的事情。
我确实有这个表单的域模型(尽管它的字段比表单包含的字段多。其余字段在以下页面的表单中设置 - 就像设置向导一样):
class UserRegistrationEntity {
String nickName;
String email;
String confirmEmail;
String password;
String confirmPassword;
}
Run Code Online (Sandbox Code Playgroud)
我可以像这样创建模型:
final userRegistration = UserRegistrationEntity();
Run Code Online (Sandbox Code Playgroud)
但是我现在如何将nickName的字段绑定userRegistration到我的表单控件?我期望表单库有一个相当于ngModel字段,以便我在表单控件上设置模型的字段。
或者这不是 Flutter 中所做的事情?
示例:https://angular.io/api/forms/NgModel#using-ngmodel-on-a-standalone-control
Fer*_*nd 4
从我reactive_forms在 flutter 中的使用来看,我还没有看到任何与ngModel. 这是因为像这样的元素ReactiveTextField被设计为具有与小部件的双重绑定功能(双向绑定)
这就是为什么你不包含像 之类的属性onChanged,这与 ngModel 方法类似#ngOnChanges()
因此,要将 userRegistration 的 nickName 字段绑定到表单控件,您可以使用 aViewModel和Provider。
所以你的代码看起来像这样:
class YourViewModel {
final _form = FormGroup({
'nickName':
FormControl<String>(validators: [Validators.required]),
});
//assuming you are signing in
void signIn() {
final credentials = this.form.value;
//the rest of your signIn code
}
}
Run Code Online (Sandbox Code Playgroud)
class YourScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final viewModel = Provider.of<YourViewModel>(context, listen: false);
return ReactiveForm(
formGroup: viewModel.form,
child: Column(
children: <Widget>[
ReactiveTextField(
formControlName: 'nickName',
),
ReactiveFormConsumer(
builder: (context, form, child) {
return RaisedButton(
child: Text('Submit'),
// if the form is valid, sign-in or whatever you need to do with the form data (I have used signIn)
onPressed: form.valid ? viewModel.signIn : null,
);
},
),
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
结论
ngModel 是一个绑定输入的指令,Reactive Forms 也做同样的事情,保持视图和模型之间的分离,同时仍然维持数据同步。因此,没有明显的需要将数据绑定到域层,而是reactive_forms完全不需要这样做,因为该过程是内置的。
| 归档时间: |
|
| 查看次数: |
4304 次 |
| 最近记录: |