by @kodeazy

flutter how to use this keyword in dart file?

Home » flutter » flutter how to use this keyword in dart file?
  • In this tutorial we will be discussing about this keyword in flutter dart file
  • this keyword is used to refer to current instance.
  • It points to the current class object.
  • Lets take an example with out using this inside a class.

    void main() {
    Student s = Student(15, 'SAM');
    s.details();
    }
    class Student {
    int age = 10;
    String name = "Zohn";
    
    Student(int age, String name) {
    age = age;
    name = name;
    }
    details() {
    print('Age is $age');
    print('Name is $name');
    }
    }

    Output:

    Age is 10
    Name is Zohn
  • Here age and name of the student is not updated because they are local variables so we are updating the variables of Constructor
  • To update class variables we use this keyword as below.

    void main() {
    Student s = Student(15, 'SAM');
    s.details();
    }
    class Student {
    int age = 10;
    String name = "Zohn";
    
    Student(int age, String name) {
    this.age = age;
    this.name = name;
    }
    details() {
    print('Age is $age');
    print('Name is $name');
    }
    }

    Output:

    Age is 15
    Name is SAM
  • Here by using this keyword we updated the variables of class
  • Hence the details are modified.

-UNDER MAINTAINANCE.