Mastering Dart: A Deep Dive into 'this' Keyword

Mastering Dart: A Deep Dive into 'this' Keyword

Introduction

Welcome to our comprehensive guide on mastering Dart programming! In this blog post, we're about to dive deeply into one of Dart's essential keywords: 'this'. Don't worry if you're new to programming or if you find these concepts a bit intimidating – we'll break them down into simple, easy-to-understand explanations with plenty of examples to help you grasp them quickly.

Understanding 'this' keyword

The this keyword is used to refer to the current class instance. this can be used to invoke the current class’s constructors or methods. It also helps access the current class’s instance variables. The this keyword can be used to set the instance variable’s values or get the current instance of the class.

Why use thethis keyword?

Suppose the declared class attributes are the same as the parameter name, and the program becomes ambiguous. We can eliminate this ambiguity by prefixing the class attributes with the this keyword.

The this keyword can be given as an argument to the constructors or methods of the class.

Example

The example below demonstrates how to use the this keyword to call an instance variable.

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

class Person {
  double? height;
  Person(double height) {
    height = height; //You are confused right? same is the compiler.
  }
}

Upon executing this Dart code, it outputs null for the height. This occurs because the expression height = height within the Person constructor creates ambiguity regarding the class property 'height'.

To resolve this ambiguity, we employ the 'this' keyword, signifying the current instance. This aids the code in discerning which 'height' pertains to the class. Therefore, by utilizing 'this' as illustrated below, we obtain the accurate output.

Therefore the correct code would be:

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

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

Now, let's examine another example to gain a deeper understanding.

class Person {
  String? name;

  Person(String name){
    this.name = name; // Assigning parameter 'name' to instance variable 'name' using 'this'
  }

  void greet() {
    print('Hello, my name is $name');
  }

  void introduce() {
    print('Allow me to introduce myself...');
    this.greet(); // Using 'this' to call the greet() method
  }
}

void main() {
  var person = Person('Nibu');
  person.introduce();
}
Output:
Allow me to introduce myself...
Hello, my name is Nibu

In the code provided, the parameter 'name' in the constructor of the Person class shares the same name as the instance variable 'name'.

This creates ambiguity about which 'name' is being referenced. To clarify, the 'this' keyword is used to explicitly refer to the instance variable 'name', ensuring correct assignment and eliminating confusion.

Exercises

Multiple Choice Questions

  • Which keyword in Dart is used to refer to the current instance of a class?

    a) super

    b) this

    c) static

    d) abstract

  • What does the 'this' keyword help to resolve?

    a) Ambiguity between class constructors

    b) Accessing static variables

    c) Defining abstract methods

    d) Invoking superclass methods

Code Completion

  • Complete the following code snippet by using the 'this' keyword appropriately:
class Person {
  String? name;

  Person(String name){
    // Complete the constructor to assign 'name' parameter to 'name' instance variable
    this._______ = _______;
  }
}

Debugging Exercise

  • Identify and correct the error in the following code snippet:

  •       Rectangle {
            int? width;
            int? height;
    
            Rectangle(int width, int height) {
              width = width;
              height = height;
            }
          }
    

Answers

Multiple Choice Questions

  • Which keyword in Dart is used to refer to the current instance of a class?

    Answer: b) this

  • What does the 'this' keyword help to resolve?

    Answer: a) Ambiguity between class constructors

Code Completion

  • Complete the following code snippet by using the 'this' keyword appropriately:
class Person {
  String? name;

  Person(String name){
    // Complete the constructor to assign 'name' parameter to 'name' instance variable
    this.name= name;
  }
}

Debugging Exercise

  • Identify and correct the error in the following code snippet:
class Rectangle {
  int? width;
  int? height;

  Rectangle(int width, int height) {
    // Assign the 'width' and 'height' parameters to the instance variables using 'this' keyword
    this.width = width;
    this.height = height;
  }
}

Takeaway

  1. It refers to the current instance of the class.

  2. It can be used to access instance variables and methods within the class.

  3. It helps resolve ambiguity when class attributes share the same names as parameters.

  4. It is particularly useful in constructor chaining.

  5. It can be passed as an argument to methods or constructors.

  6. It aids in distinguishing between local and instance variables within the class.

Further Reading