I get an error such as:
Instance members can't be accessed from a factory constructor. Try removing the reference to the instance member.
Any solutions?
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);
},
),
);
}
CodePudding user response:
You need to make some changes to your code to make it work. Use below model
or make change in daysofweek
line in your model
like below :
import 'dart:convert';
DepartureModel departureModelFromJson(String str) => DepartureModel.fromJson(json.decode(str));
String departureModelToJson(DepartureModel data) => json.encode(data.toJson());
class DepartureModel {
DepartureModel({
this.route,
this.departureTime,
this.arrivalTime,
this.tourType,
this.daysOfWeek,
});
String route;
String departureTime;
String arrivalTime;
String tourType;
List<String> daysOfWeek;
factory DepartureModel.fromJson(Map<String, dynamic> json) => DepartureModel(
route: json["route"],
departureTime: json["departureTime"],
arrivalTime: json["arrivalTime"],
tourType: json["tourType"],
daysOfWeek: List<String>.from(json["daysOfWeek"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"route": route,
"departureTime": departureTime,
"arrivalTime": arrivalTime,
"tourType": tourType,
"daysOfWeek": List<dynamic>.from(daysOfWeek.map((x) => x)),
};
}
CodePudding user response:
You are trying to access daysOfWeek
while assigning it, this is why the compiler is complaining as it doesn't yet know the value of daysOfWeek
.
A really valid workaround would be to create a new list in the factory constructor and after you are done looping you assign that to daysOfWeek
as such:
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,
);
You can also name tempDaysOfWeek
as daysOfWeek
as scope will take care of which variable is being called but this alleviates confusion.
Also a more concise usage without the forEach
can be as follows:
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>(),
);