Flutter中的copyWith是什么?

问题描述 投票:0回答:1
//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在代码中做什么?谢谢!

flutter dart stream bloc
1个回答
0
投票

假设您有一个要在其中更改某些属性的对象。一种方法是一次更改每个属性,例如object.prop1 = x object.prop2 = y等。如果要更改的属性太多,这将变得很麻烦。然后copyWith方法就派上用场了。此方法获取所有属性(需要更改)及其相应的值,并返回具有所需属性的新对象。

[updateWith方法通过再次调用copyWith方法来做同样的事情,最后将返回的对象推送到流中。

© www.soinside.com 2019 - 2024. All rights reserved.