thumbnail

Classes In Dart - This Keyword

Published on 29 March 2020
Last Updated on 29 March 2020

This page documents how this keyword can be used effectively while defining classes in Dart.

this keyword can be used for initializing un-initialized variables.

Following are the various uses for this keyword in Dart:

  • This keyword can be used as a syntactic sugar for initializing un-initialzed variables in Dart.
  • This keyword can also be used for referring to the current instance of a Class.
  • Use this keyword to avoid name conflicts while passing new arguments to methods in Dart.
  • This keyword can be passed as an argument to a method call.
  • This keyword can be used to return current instance of a Class.
  • This keyword can be used to invoke current class method.

Programs to demonstrate various uses of this keyword

Given below is a program that demonstrates how this keyword can be used in Dart programming language.

This keyword used as syntactic sugar for initializing variables

// program to demonstrate use of this keyword in Dart

class Person {
  final String name;
  // this keyword used as syntactic sugar for initializing variables
  Person(this.name);
}

main(List<String> args) {
  var person = new Person('abc');
  print('person.name is: ${person.name}');
}

Above program produces following output:

person.name is: abc

As shown in above program, this.name is used as syntactic sugar for initializing un-initialized variables.

Referring to the current instance of a Class using This Keyword

// program to demonstrate use of this keyword in Dart

class Person {
  final String _name;
  // this keyword used as syntactic sugar for initializing variables
  Person(this._name);

  void printName() {
    print('person.name is: ${this._name}');
  }
}

main(List<String> args) {
  var person = new Person('abc');
  person.printName();
}

Above program produces following output:

person.name is: abc

As shown in above program, this keyword is used for accessing fields of the current instance of the class.

Above programs demonstrate common use cases for this keyword in dart.

Factory constructor in Dart

Please note that factory constructors in Dart do not have access to this keyword.

We hope that you have found this guide useful.