What is copyWith and how do we use it in Flutter?
Let's say you have an object in which you want to change some properties. One way to do is by changing each property at a time like object.prop1 = x
object.prop2 = y
and so on. This will go cumbersome if you have more than few properties to change. Then copyWith
method comes handy. This method takes all the properties(which need to change) and their corresponding values and returns new object with your desired properties.
updateWith
method is doing same thing by again calling copyWith
method and at the end it is pushing returned object to stream.
Lets say you have a class like it:
class PostSuccess {
final List<Post> posts;
final bool hasReachedMax;
const PostSuccess({this.posts, this.hasReachedMax});
functionOne(){
///Body here
}
}
Lets say you want to change some properties of the class on the go, What you can do you can declare the copyWith method like that:
PostSuccess copyWith({
List<Post> posts,
bool hasReachedMax,
}) {
return PostSuccess(
posts: posts ?? this.posts,
hasReachedMax: hasReachedMax ?? this.hasReachedMax,
);
}
As you see, in the return section, you can change the value of the properties as required by your situation and return the object.