Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does @override toString method do in a Flutter Dart class?

Tags:

flutter

dart

In the following model class, what purpose does overriding the toString() method achieve?

class User {
  final int id;
  String name, email, token;

  User(this.id, this.name, this.email, this.token);

  User.fromJson(dynamic json) : this.id = json['id'] {
    this.name = json['name'];
    this.email = json['email'];
    this.token = json['token'];
  }

  dynamic toJson() => {'id': id, 'name': name, 'email': email, 'token': token};

  @override
  String toString() {
    return toJson().toString();
  }
}
like image 783
Javeed Ishaq Avatar asked Nov 14 '20 16:11

Javeed Ishaq


People also ask

What happen if we override toString () method?

By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.

Why we do override toString ()?

Overriding toString() Method in Java out. print. It is because this method was getting automatically called when the print statement is written. So this method is overridden in order to return the values of the object which is showcased below via examples.

What is toString in Dart?

String toString () override. Returns the shortest string that correctly represent the input number. All doubles in the range 10^-6 (inclusive) to 10^21 (exclusive) are converted to their decimal representation with at least one digit after the decimal point.

What is toString in flutter?

String toString() Returns a string representation of this integer. The returned string is parsable by parse. For any int i , it is guaranteed that i == int.


Video Answer


1 Answers

The purpose of the toString() method is to provide a literal representation of whatever object it is called on, or to convert an object to a string (example converting primitive types to strings). For a user defined class, it can vary depending on your use case. You might want to print out the object to a console. A simple print command on the object won't give you any useful information. However, you can use the toString() method and convert it to a more understandable version. Example

@override
String toString() {
    return "($someProperty,$someOtherProperty)";
}

This will return whatever the properties of that object were set at that time. Another (although not good) purpose could be to compare two objects of the same class. Similar to the above example, you can say that two objects of the class would be equal if the output of the toString() method of both objects is the same. Again, it totally depends on your use case.

like image 176
Bilal Naeem Avatar answered Oct 20 '22 01:10

Bilal Naeem