Home > Mobile >  final model properties in flutter
final model properties in flutter

Time:12-06

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.

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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

  • Related