//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,并且还创建了一个Model类。我的问题是,copyWith({})是什么?它对email_sign_in_model和那个email_sign_in_bloc做什么?那updateWith在代码中做什么?谢谢!
答案 0 :(得分:3)
假设您有一个要在其中更改某些属性的对象。一种方法是一次更改每个属性,例如object.prop1 = x
object.prop2 = y
,依此类推。如果您要更改的属性过多,这将变得很麻烦。然后copyWith
方法就派上用场了。此方法将获取所有需要更改的属性及其对应的值,并返回具有所需属性的新对象。
updateWith
方法通过再次调用copyWith
方法来做同样的事情,最后将返回的对象推送到流中。
答案 1 :(得分:3)
让我们说您有一个像这样的班级:
class PostSuccess {
final List<Post> posts;
final bool hasReachedMax;
const PostSuccess({this.posts, this.hasReachedMax});
functionOne(){
///Body here
}
}
让我们说您想随时随地更改类的某些属性,可以做什么,可以这样声明copyWith方法:
PostSuccess copyWith({
List<Post> posts,
bool hasReachedMax,
}) {
return PostSuccess(
posts: posts ?? this.posts,
hasReachedMax: hasReachedMax ?? this.hasReachedMax,
);
}
如您所见,在返回部分,您可以根据情况更改属性的值并返回对象。