Home > Back-end >  What's the difference between a normal method and a setter method in Dart?
What's the difference between a normal method and a setter method in Dart?

Time:01-11

I just stared learning Dart yesterday. I want to know what's the difference between a normal method and a setter method in Dart? For example, I have the following demo code.

class Person {
  String? firstName;
  String? lastName;

  // Normal method
  fullName(String? name) {
    var names = name!.split(' ');
    this.firstName = names[0];
    this.lastName = names[1];
  }
}

main() {
  Person p = Person();
  p.fullName('John Smith');
  print("${p.firstName} ${p.lastName}");
}

And:

class Person {
  String? firstName;
  String? lastName;

  // Setter
  set fullName(String? name) {
    var names = name!.split(' ');
    this.firstName = names[0];
    this.lastName = names[1];
  }
}

main() {
  Person p = Person();
  p.fullName = 'John Smith';
  print("${p.firstName} ${p.lastName}");
}

The difference seems only the invocation syntax. Besides that, are there any other differences?

CodePudding user response:

It mostly comes down to conventions.

Generally you wouldn't want a setter without a getter. (Although getters without setters are fine...and common.)

In your case, I'd use a setter – and just add a getter!

(Although I'd add more checking to the setter to make sure someone doesn't pass in "A string with more spaces!").

  •  Tags:  
  • Related