dart Error: Field ‘xxx’ should be initialized because its type ‘String’ doesn’t allow null

苍池1年前561

有的同学在用dart class的构造函数时候会出现 这个问题
020202.png

原因是firstName没有初始化,不能为null
解决方案:
1.在String后面加个?

PHP
class Person {
  String? firstName ;
  Person.fromJson(Map data) {
    print('in Person');
  }}



2.使用late关键字

PHP
class Person {
  late String firstName ;
  Person.fromJson(Map data) {
    print('in Person');
  }}



完整代码:

PHP
class 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 转载需授权!

网友评论

最新发布

扫一扫二维码,添加客服微信