什么是 copyWith 以及如何在 Flutter 中使用它以及它的用例是什么?
//File: email_sign_in_model.dart
class EmailSignInModel {
EmailSignInModel({
this.email='',
this.formType=EmailSignInFormType.signIn,
this.isLoading=false,
this.password='',
this.submitted=false,
});
final String email;
final String password;
final EmailSignInFormType formType;
final bool isLoading;
final bool submitted;
EmailSignInModel copyWith({
String email,
String password,
EmailSignInFormType formType,
bool isLoading,
bool submitted,
}) {
return EmailSignInModel(
email: email ?? this.email,
password: password?? this.password,
formType: formType?? this.formType,
isLoading: isLoading?? this.isLoading,
submitted: submitted?? this.submitted
);
}
}
//File: email_sign_in_bloc.dart
import 'dart:async';
import 'package:timetrackerapp/app/sign_in/email_sign_in_model.dart';
class EmailSignInBloc {
final StreamController<EmailSignInModel> _modelController = StreamController<EmailSignInModel>();
Stream<EmailSignInModel> get modelStream => _modelController.stream;
EmailSignInModel _model = EmailSignInModel();
void dispose() {
_modelController.close();
}
void updateWith({
String email,
String password,
EmailSignInFormType formType,
bool isLoading,
bool submitted
}) {
//update model
_model = _model.copyWith(
email:email,
password: password,
formType: formType,
isLoading: isLoading,
submitted: submitted
);
//add updated model _tomodelController
_modelController.add(_model);
}
}
我是 Flutter 和 dart 的新手,并试图在 Flutter 中学习 bloc,我正在尝试使用 BLOC 并且还创建了一个模型类.我的问题是 copyWith({}) 是什么,它对 email_sign_in_model 和 email_sign_in_bloc 做了什么?代码中的 updateWith 是做什么的?谢谢!
Hi, I am new to Flutter and dart and trying to learn bloc in Flutter, I am trying to use BLOC and the also created a model class. My question is What is that copyWith({}) and what it is doing for the email_sign_in_model and for that email_sign_in_bloc? and what is that updateWith doing in the code? Thank you!
假设您有一个要更改某些属性的对象.一种方法是一次更改每个属性,例如 object.prop1 = x
object.prop2 = y
等等.如果要更改的属性太多,这将变得很麻烦.然后 copyWith
方法就派上用场了.此方法获取所有属性(需要更改)及其对应的值,并返回具有所需属性的新对象.
Let's say you have an object in which you want to change some properties. One way to do is by changing each property at a time like object.prop1 = x
object.prop2 = y
and so on. This will go cumbersome if you have more than few properties to change. Then copyWith
method comes handy. This method takes all the properties(which need to change) and their corresponding values and returns new object with your desired properties.
updateWith
方法通过再次调用 copyWith
方法来做同样的事情,最后它将返回的对象推送到流中.
updateWith
method is doing same thing by again calling copyWith
method and at the end it is pushing returned object to stream.