dart Error: Field ‘xxx’ should be initialized because its type ‘String’ doesn’t allow null
有的同学在用dart class的构造函数时候会出现 这个问题
原因是firstName没有初始化,不能为null
解决方案:
1.在String后面加个?
PHPclass Person { String? firstName ; Person.fromJson(Map data) { print('in Person'); }}
2.使用late关键字
PHPclass Person { late String firstName ; Person.fromJson(Map data) { print('in Person'); }}
完整代码:
PHPclass Person { late String firstName ; Person.fromJson(Map data) { print('in Person'); }}class Employee extends Person { // Person does not have a default constructor; // you must call super.fromJson(data). Employee.fromJson(Map data) : super.fromJson(data) { print('in Employee'); }}main() { var emp = new Employee.fromJson({}); // Prints: // in Person // in Employee if (emp is Person) { // Type check emp.firstName = 'Bob'; } (emp as Person).firstName = 'Bob';}
本文链接:https://www.cangchiyun.cn/cangchi/18.html 转载需授权!