【问题标题】:What is copyWith and how can I use it in Flutter and what is it's use case?什么是 copyWith,我如何在 Flutter 中使用它,它的用例是什么?
【发布时间】:2020-10-03 22:36:06
【问题描述】:
//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 在代码中做了什么?谢谢!

【问题讨论】:

标签: forms flutter dart stream bloc


【解决方案1】:

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

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

【讨论】:

  • 在最后返回 EmailSignInModel(email: email??this.email,.............)........哪个值 ' this.email' 指的是什么?它是否引用了第一个创建的类,它在顶部的构造函数的默认值?
【解决方案2】:

假设你有一个类似的课程:

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,
    );
  }
  

如您所见,在返回部分,您可以根据自己的情况更改属性的值并返回对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-11
    • 2011-07-31
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    相关资源
    最近更新 更多