简体   繁体   中英

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

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();
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM