我收到一个错误,例如:
无法从工厂构造函数访问实例成员。尝试删除对实例成员的引用。
有什么解决办法吗?
class DepartureModel {
String route;
String departureTime;
String arrivalTime;
String tourType;
List<String> daysOfWeek;
DepartureModel({
required this.route,
required this.departureTime,
required this.arrivalTime,
required this.tourType,
required this.daysOfWeek,
});
//method that assign values to respective datatype vairables
factory DepartureModel.fromJson(Map<String, dynamic> json) {
return DepartureModel(
route: json['route'],
departureTime: json['departureTime'],
arrivalTime: json['arrivalTime'],
tourType: json['tourType'],
daysOfWeek: json["daysOfWeek"].forEach(
(day) {
daysOfWeek.add(day);
},
),
);
}
Run Code Online (Sandbox Code Playgroud)
您试图daysOfWeek
在分配它时访问它,这就是编译器抱怨的原因,因为它还不知道 的值daysOfWeek
。
一个真正有效的解决方法是在工厂构造函数中创建一个新列表,并在完成循环后将其分配给daysOfWeek
这样的:
factory DepartureModel.fromJson(Map<String, dynamic> json) {
final tempDaysOfWeek = [];
json["daysOfWeek"].forEach((day) => tempDaysOfWeek.add(day));
return DepartureModel(
route: json['route'],
departureTime: json['departureTime'],
arrivalTime: json['arrivalTime'],
tourType: json['tourType'],
daysOfWeek: tempDaysOfWeek,
);
Run Code Online (Sandbox Code Playgroud)
您还可以命名tempDaysOfWeek
为daysOfWeek
作用域将负责调用哪个变量,但这可以减轻混乱。
不带 的更简洁用法如下forEach
:
factory DepartureModel.fromJson(Map<String, dynamic> json) {
return DepartureModel(
route: json['route'],
departureTime: json['departureTime'],
arrivalTime: json['arrivalTime'],
tourType: json['tourType'],
daysOfWeek: (json["daysOfWeek"] as List).cast<String>(),
);
Run Code Online (Sandbox Code Playgroud)