3

in the flutter when you are defining a model. the convention is to define properties as final and write a copyWith for class instead of defining non-final vars and removing the copyWith method. what is the exact reason for this? is it a flutter performance thing?

for example:

class Emplyee {
  final String name;
  final String id;

  Emplyee({required this.name, required this.id});

  Emplyee copyWith({String? name, String? id}) {
    return Emplyee(id: id ?? this.id, name: name ?? this.name);
  }

  Map<String, dynamic> toJson() => {
        "name": name,
        "id": id,
      };

  Emplyee.fromJson(Map<String, dynamic> json)
      : name = json["name"],
        id = json["id"];
}

P.S. I know this convention makes sense in widgets. but my question is about data model classes.

reza
  • 1,354
  • 1
  • 7
  • 25

4 Answers4

3

Immutability reduces the risk of errors by side effects. Have a look at this code:

class User {
  String name;
  
  User({required this.name});
}


void main() {

  final user = User(name: 'Stefan');
  someFunction(user);
  print(user.name);
  
}

someFunction(User user){
  user.name = 'Thomas';
}

This snippet prints 'Thomas' because the function manipulates the user object. In the main function, you have no chance to know what happens with the object.

With immutability, this would not be possible. It would be necessary to create a new instance of User to have a User named 'Thomas'. The instance in the main function would be the same.

Stefan Galler
  • 781
  • 4
  • 12
1

It's for Immutability. Mutable class is error-prone.

聂超群
  • 1,659
  • 6
  • 14
  • my question is why data classes should be immutable? – reza Dec 06 '21 at 09:32
  • So basically you want your data class to be immutable so that it can hold data that cannot change. Then if you want to mutate the state, then you can just create a copy instance and then mutate it without affecting the actual class itself. – Denzel Dec 06 '21 at 09:56
1

So basically the copyWith method makes it possible for you to create a new instance of the class and then you can edit whatever you want in this new instance of the class, without affecting data in the original class. So that's what the copyWith method does, I don't think it's for performance, I think it just aids some coding use cases.

Denzel
  • 942
  • 5
  • 14
1

Using final makes a class immutable.

You can check Why do we need immutable class?

Immutable class is good for caching purpose and it is thread safe.

The reason behind using copyWith() is flexible, allowing any number of properties to be updated in a single call.

More about immutable-data-patterns-in-dart-and-flutter

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56