Solved: Instance members can't be accessed from a factory constructor. Flutter error

Question

Asked by devfoz on January 03, 2022 (source).

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);
        },
      ),
    );
  }

Answer

Question answered by Ayman B (source).

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>(),
    );
DART FLUTTER HTTP
SHARE: