mustafa hasria
mustafa hasria

Reputation: 510

what is deferent between get method and regular method dart

Good day, I am new with dart and I have two questions here

  1. what is deferent between (double get getName => name) , (double getName => name)
  2. sometimes I see method name with "." when we use this concept and what we call it Thank you.

Upvotes: 1

Views: 813

Answers (2)

Benedikt J Schlegel
Benedikt J Schlegel

Reputation: 1939

double get name{

}

is what is called a "Getter". It is a way of exposing a value to outside of that class, for instance if you have a private variable _name and you want it to be readable from the outside, but not changeable, you might use a getter

double getName(){

}

is just a normal function. the arrow syntax is just a shortened version of returning a value. So:

int get x => _x;

and

int get x {
return _x;
}

are essentially the same. For some more reading on functions and getters/setters, have a look at these links.

https://dev.to/newtonmunene_yg/dart-getters-and-setters-1c8f https://zetcode.com/dart/function/ (also has a section on arrow functions)

EDIT:

For your second question:

  factory LoginResponse.fromJson(Map<String, dynamic> json) => LoginResponse(
        user: User.fromJson(json["user"]),
        accessToken: json["access_token"],
      );

In that case, this is a named factory constructor with the name "fromJson" that takes a Map<String,dynamic> and returns a LoginResponse that is being created using the LoginResponse(user, accessToken) constructor.

You would call it like so:

var response = new LoginResponse.fromJson(json);

More about named constructors here:

https://www.tutorialspoint.com/dart_programming/dart_programming_classes.htm#:~:text=Dart%20defines%20a%20constructor%20with,constructor%20is%20provided%20for%20you.

Upvotes: 2

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12363

By using double get getName => name , you are defining 'getName' as a getter. Where you are requesting the value of getname from outside a class. Whenever you call getName, the value of name will be returned.

Regarding double getName => name , it should be written like this double getName() => name. By using this, you are basically telling your code:

double getName(){
return name;}

Meaning, the value of getName is returned from a function.

If you wrote double getname(int x) => x + name the will run as :

double getName(int x){
return x + name;}

Upvotes: 0

Related Questions