Dart – How to print an object

When writing code, in any kind of project, you will need to display the log to visualize the data on console window. In this post, we will learn how to print an object beautifully. Dart provides print() method to do this. With primitive types (like int, String…) this method works perfectly. But when you print a custom object, the output may make you un-happy. Let’s try an example:

Suppose we have a Student class with name and age:

class Student {
  final String name;
  final int age;

  Student(this.name, this.age);
}


Then we create an instance of Student and print it out:

main() {
  var student = Student('Coflutter', 30);
  print(student);
}


The output will be:

Instance of 'Student'


Nothing wrong with this output but we expect to see the details of the created student instead. We will modify our code to decorate the output, but before that let’s understand why it shows “Instance of ‘ClassName'” but nothing else.

– In Dart, everything you can place in a variable is an object. That means when you create a new class, your class inherits Object class.

– When we call print( ) method, it will print the String returned from toString() method in your class. Hence, if you don’t override toString() method in your class, the toString()method under Object class will be used. That’s why you see “Instance of ‘ClassName’”:

toString() {
    return "Instance of '" + dart.typeName(dart.getReifiedType(this)) + "'";
}


Therefore, what we need to do is simply overriding the toString() method in our Student class:

class Student {
  final String name;
  final int age;

  Student(this.name, this.age);

  @override
  String toString() {
    return 'Student: {name: ${name}, age: ${age}}';
  }
}


That’s it and here is the beautified version which may make you happier!

Student: {name: Coflutter, age: 30}
Tagged : / / / / / /
5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x