Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final model properties in flutter

Tags:

flutter

dart

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.

like image 800
reza Avatar asked Sep 23 '26 10:09

reza


2 Answers

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.

like image 58
Stefan Galler Avatar answered Sep 25 '26 13:09

Stefan Galler


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

like image 43
聂超群 Avatar answered Sep 25 '26 14:09

聂超群



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!