//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);
}
}
Hallo, ich bin neu bei Flutter und Dart und versuche, Block in Flutter zu lernen. Ich versuche, BLOC zu verwenden, und habe auch eine Modellklasse erstellt. Meine Frage ist, was ist das copyWith({}) und was macht es für das email_sign_in_model und für das email_sign_in_bloc? und was macht das updateWith im Code? Danke!
Lösung des Problems
Angenommen, Sie haben ein Objekt, bei dem Sie einige Eigenschaften ändern möchten. Eine Möglichkeit, dies zu tun, besteht darin, jede Eigenschaft nacheinander zu ändern, z. B. object.prop1 = x
object.prop2 = y
usw. Dies wird umständlich, wenn Sie mehr als nur wenige Eigenschaften ändern müssen. Dann copyWith
ist die Methode praktisch. Diese Methode nimmt alle Eigenschaften (die geändert werden müssen) und ihre entsprechenden Werte und gibt ein neues Objekt mit Ihren gewünschten Eigenschaften zurück.
updateWith
Die Methode macht dasselbe, indem sie die copyWith
Methode erneut aufruft und am Ende das zurückgegebene Objekt in den Stream drückt.
Keine Kommentare:
Kommentar veröffentlichen