Dart Tutorials

Dart Override toString() method In a class

If you have a class and you override the toString() method, it will return such a string method when the instance/object of the class is printed.

Why? when you create an object of a class and you print it to the console. It only returns the address of that object in the system memory.

For example, if we create an object of class A as shown below.

A a =new A();
Print(a);

Above code will print the address of the “a” object in the memory as adadads:A or Instance of A

So note that the toString() method in a class will only override the return of address location when the instance/object of the class is printed to the console.

Example:

// Create a class
class Name {
  String name = "justice";
  int age = 23;

  // override the toString method and return some String when the object/instance of this class is printed
  @override
  String toString() {
    // am returning the above class properties
    return this.name + " " + this.age.toString();
  }
}

 void main() {
  // create object/instance of the above class
  Name name = new Name();
  /* 
  If you print an object/instance of a class and that class override the toString method, 
  it will invoke the toString method implicitly instead of returning the instance address of the class.
  */
  print(name);
  // So because the below "Name" class override the toString methods the result will be: justice 23
 // if the "Name" class didn't override the toString method, then the result will be: Instance of 'Name' or Locatio address 
 }

Related Posts

working with list in Dart/Flutter

Working with List in Dart/Flutter

A list is a way of storing data in a list of order. In other programming, languages like PHP and javascript Array is used as a list. List…

working with list in Dart/Flutter

Null Safety in Dart and Flutter

By default, all Dart variables and methods are non-nullable, meaning they can’t be or return null. So, to make a variable or method nullable, meaning to be or…

working with list in Dart/Flutter

Working with DateTimes in Dart Or Flutter with examples

The DateTime class provides methods to work with dates and times when developing flutter or dart applications. An example could be an instance in time of June 20,…