简体   繁体   English

@override toString 方法在 Flutter Dart class 中做了什么?

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

In the following model class, what purpose does overriding the toString() method achieve?下面model class中,重写toString()方法达到什么目的?

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). toString()方法的目的是提供调用它的任何 object 的文字表示,或将 object 转换为字符串(例如将原始类型转换为字符串)。 For a user defined class, it can vary depending on your use case.对于用户定义的 class,它可能因您的用例而异。 You might want to print out the object to a console.您可能希望将 object 打印到控制台。 A simple print command on the object won't give you any useful information. object 上的简单打印命令不会为您提供任何有用的信息。 However, you can use the toString() method and convert it to a more understandable version.但是,您可以使用 toString() 方法并将其转换为更易于理解的版本。 Example例子

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

This will return whatever the properties of that object were set at that time.这将返回当时设置的 object 的任何属性。 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.另一个(虽然不好)目的可能是比较相同 class 的两个对象。与上面的示例类似,如果两个对象的toString()方法的 output 是相同的。 Again, it totally depends on your use case.同样,这完全取决于您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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