dart中的构造函数与Swift中的构造函数比较

nhaq1z21  于 2023-03-15  发布在  Swift
关注(0)|答案(2)|浏览(148)

来自斯威夫特,这在斯威夫特很好用-

class Test {
    let userId: Int?
    let id: Int?
    let title: String?
    
    init(userId: Int, id: Int, title: String) {
        self.id = id
        self.title = title
        self.userId = userId
    }
    
}

现在,在尝试dart文档时,我尝试了这个方法,它工作正常

class Album {
   int? userId;
  int? id;
  String? title;

    Album({required int userId, required int id, required String title}) {
     this.userId = userId;
     this.id = id;
     this.title = title;
   }
  
}

但如果我要添加最终关键字,这是像让在swift它停止工作,我必须做一些事情,如下面-

class Album {
   final int? userId;
   final int? id;
    final String? title;

  
    const Album({required this.id, required this.userId, required this.title});
}

我不知道为什么这个工作,为什么下面的不-这只是我必须开始做的事情,或者背后有任何逻辑以及-

class Album {
   final int? userId;
   final int? id;
    final String? title;

    Album({required int userId, required int id, required String title}) {
     this.userId = userId;
     this.id = id;
     this.title = title;
   }
   
}
nfg76nw0

nfg76nw01#

你可以使用一个初始化器列表来初始化构造函数外部的final变量,如下所示:

class Album {
  final int? userId;
  final int? id;
  final String? title;

  Album({required int userId, required int id, required String title}) :
    this.userId = userId,
    this.id = id,
    this.title = title;

}

但是对于这个例子,你真的应该把它写成

class Album {
  final int? userId;
  final int? id;
  final String? title;

  Album({required int this.userId, required int this.id, required String this.title});

}

这样更符合习惯,更简洁。没有理由用另外一种方式来写。

voase2hg

voase2hg2#

Dart空安全。您可以使用late关键字。

class Album {
  late final int? userId;
  late final int? id;
  late final String? title;

  Album({required int userId, required int id, required String title}) {
    this.userId = userId;
    this.id = id;
    this.title = title;
  }
}

但是对于同名的更好的做法是

class Album {
  final int? userId;
  final int? id;
  final String? title;
  const Album({
    this.userId,
    this.id,
    this.title,
  });
}

更多关于null-safety的信息。

相关问题