首页 > 解决方案 > `toString` 方法将 null 添加到 Dart 中的对象

问题描述

我正在开发一个 Flutter Web 应用程序,并且正在使用自定义类来跟踪表单数据。我正在实例化以下类的新实例:

class Contact {
  String name;
  String relationship;
  String phoneNo;

  @override
  String toString() {
    print("""{
      Name: $name,
      Relation: $relationship,
      Phone: $phoneNo
    }""");
  }
}

在我的控制器中,一旦实例化,我就会立即打印出值:

// Method in controller, triggered by onTap
Contact contact = Contact();
print(contact);

输出是:

{
      Name: null,
      Relation: null,
      Phone: null
    }
null

values这会导致以后出现问题,因为此类的实例被用作HashMap. 我已将问题缩小到由该toString方法引起的问题,当我删除它Instance of 'Contact'时,会根据需要打印出来。处理这个问题的最佳方法是什么?

标签: dart

解决方案


// Method in controller, triggered by onTap
Contact contact = Contact();
print(contact);

您创建了一个不带参数的 Contact 新实例,这就是为什么 Contact 的所有值都是null.

要分配一个值,有两种解决方案:

1.从类本身内部:

class Contact {
  String name = 'John doe';
  String relationship = 'Brother';
  String phoneNo = '1234567890';

  @override
  String toString() {
    print("""{
      Name: $name,
      Relation: $relationship,
      Phone: $phoneNo
    }""");
  }
}

2.来自课外

为此,您必须在您的班级中启动 Constructor

class Contact {
  String name;
  String relationship;
  String phoneNo;

  Contact(this.name, this.relationship, this.phoneNo);
  //You can also choose between named parameters and positional parameters
  // For named parameters Contact({this.name, and so on....})

  @override
  String toString() => """{
      Name: $name,
      Relation: $relationship,
      Phone: $phoneNo
    }""";
}

在这种情况下,您必须在创建类实例的位置传递值,如下所示:

Contact contact = Contact('John Doe', 'brother', '123456789');
print(contact);

推荐阅读