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}

If you are looking for mobile/web Software Engineers to build you next projects, please Drop us your request!

Tagged : / / / / / /
Subscribe
Notify of
guest

10 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
mosaadIbrahim
mosaadIbrahim
1 year ago

good man

Dave
Dave
2 years ago

Another great way to do this is to use the built-in inspect() method.

sky
sky
2 years ago

how to get name and age ?

Ryzorbent
Ryzorbent
3 years ago

great, clean and elegent!

Dangdat
Dangdat
3 years ago

I love this!

Roff
Roff
3 years ago

Man!………I really love dis!…….do u hv like an app 4 easy access?

Well, 4 nw I cld jst add d website to home

Abdalla
Abdalla
3 years ago

Excellent, I was looking for this since a long time

10
0
Would love your thoughts, please comment.x
()
x