无法从工厂构造函数访问实例成员。颤动错误

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

我收到如下错误:

无法从工厂构造函数访问实例成员。 尝试删除对实例成员的引用。

有什么解决办法吗?

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

您需要对代码进行一些更改才能使其正常工作。使用下面的 model 或在 model 中的 daysofweek 行中进行更改,如下所示:

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

您在分配时试图访问 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,
    );

您也可以将 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>(),
    );