dart - `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'
时,会根据需要打印出来。处理这个问题的最佳方法是什么?
解决方案
// 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);
推荐阅读
- c++ - WinUSB 崩溃并出现错误 1450“系统资源不足,无法完成请求的服务”
- python - 从状态文件跟踪 LFTP 下载
- python - 如何从链接中没有文件名的下载 URL 获取文件名
- python - 用python用连续分布的卷积拟合数据
- c# - (ObjectDisposedException) 无法将 FormFile 上传到磁盘空间
- javascript - 在 pm2 中更改进程的端口
- c++ - 将函数指针匹配为模板参数?
- python - 按年份对出版物列表进行排序
- node.js - Heroku 上的 Node.js Web 应用程序的 Auth0 登录失败(但在 localhost 上成功)
- angular - Angular Material Sidenav 模块无法识别