sunbeam
sunbeam

Reputation: 111

What does mean of using the "this" keyword in Dart?

I'm sorry if this sounds like an extremely foolish question but it's really been bugging me.

What is the "this." that I see? Whenever I see the documentation in flutter I see it used in things like the following in the documentation:

this.initialRoute,
this.onGenerateRoute,
this.onGenerateInitialRoutes,
this.onUnknownRoute,
this.navigatorObservers

I'll be more than happy to also read up any links or documentation regarding it.

Upvotes: 9

Views: 11980

Answers (3)

Luiz Filipe Medeira
Luiz Filipe Medeira

Reputation: 1310

The 'this' keyword refers to the current instance. You only need to use this when there is a name conflict. Otherwise, Dart style omits the this.

class Car {
  String engine;

  void newEngine({String engine}) {
    if (engine!= null) {
      this.engine= engine;
    }
  }
}

So you can be consistent with the name of your parameters, either in the constructor or in some function in the class.

class Car {
  String engine;

  void updateEngine({String someWeirdName}) {
    engine = someWeirdName;
  }
}

If you don't have a name conflict, you don't need to use this.

In other languages ​​like Python and Swift, the word 'self' will do the same thing as 'this'.

Upvotes: 13

Ronak Patel
Ronak Patel

Reputation: 629

Use of this keyword

The this keyword is used to point the current class object.

It can be used to refer to the present class variables.

We can instantiate or invoke the current class constructor using this keyword.

We can pass this keyword as a parameter in the constructor call.

We can pass this keyword as a parameter in the method call.

It removes the ambiguity or naming conflict in the constructor or method of our instance/object.

It can be used to return the current class instance.

Upvotes: 3

Kalhara Tennakoon
Kalhara Tennakoon

Reputation: 1482

Basically, this keyword is used to denotes the current instance. Check out the below example.

void main() {
  
  Person mike = Person(21);
  
  print(mike.height);
  
}

class Person {
  
  double height;
  
  Person(double height) {
    height = height;

  }
}

When we run this dart code, it outputs null as the height. Because we have used height = height inside the Person constructor, but the code doesn't know which height is the class property.

Therefore, we can use this keyword to denotes the current instance and it will help the code to understand which height belongs to the class. So, we can use it as below and we will get the correct output.

void main() {
  
  Person mike = Person(21);
  
  print(mike.height);
  
}

class Person {
  
  double height;
  
  Person(double height) {
    this.height = height;

  }
}

Upvotes: 5

Related Questions