如何更改 dart 中类的打印输出/描述?

Yuc*_*ong 3 dart

例如,打击将输出Instance of 'Point'。是否可以将其重新格式化为某种形式Point(x: 0, y: 0)

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);
}

void main() {
  final zero = Point(0, 0);
  print(zero); // Instance of 'Point'
}
Run Code Online (Sandbox Code Playgroud)

在Python中,有__repr____str__ 。在Java中,有toString. 在 Swift/ObjC 中,有description. 飞镖中相当于什么?

Nas*_*sky 7

您可以覆盖toString方法:

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);

  @override
  String toString(){
    return "Point(x: $x, y: $y)";
  }
}

void main() {
  final zero = Point(0, 0);
  print(zero); // Point(x: 0, y: 0)
}
Run Code Online (Sandbox Code Playgroud)

它打印你想要的字符串。