首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >什么是copyWith,我如何在Flutter中使用它,它的用例是什么?

什么是copyWith,我如何在Flutter中使用它,它的用例是什么?
EN

Stack Overflow用户
提问于 2020-06-14 20:33:40
回答 2查看 9.7K关注 0票数 15
代码语言:javascript
运行
复制
//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);
}

}

嗨,我刚开始学习扑翼和飞镖,正在尝试学习扑翼中的积木,我正在尝试使用积木,并且还创建了一个模型类。我的问题是copyWith({})是什么,它对email_sign_in_model和email_sign_in_bloc做了什么?updateWith在代码中做了什么?谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-14 22:22:09

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

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

票数 20
EN

Stack Overflow用户

发布于 2020-09-14 10:40:51

假设你有一个这样的类:

代码语言:javascript
运行
复制
class PostSuccess {
  final List<Post> posts;
  final bool hasReachedMax;

  const PostSuccess({this.posts, this.hasReachedMax});

functionOne(){
///Body here

} 
}

假设你想在旅途中更改类的一些属性,你可以这样声明copyWith方法:

代码语言:javascript
运行
复制
PostSuccess copyWith({
    List<Post>? posts,
    bool? hasReachedMax,
  }) {
    return PostSuccess(
      posts: posts ?? this.posts,
      hasReachedMax: hasReachedMax ?? this.hasReachedMax,
    );
  }

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

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62372580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档