【问题标题】:The class 'List' doesn't have a constructor named 'fromJson'. Try invoking a different constructor, or define a constructor named 'fromJson'“List”类没有名为“fromJson”的构造函数。尝试调用不同的构造函数,或定义一个名为“fromJson”的构造函数
【发布时间】:2021-11-11 03:31:48
【问题描述】:
class Product {
    String status;
    List<List> note;
    List<List> table;

    Product({this.status, this.note, this.table});

    Product.fromJson(Map<String, dynamic> json) {
        status = json['status'];
        if (json['note'] != null) {
            note = <List>[];
            json['note'].forEach((v) { note.add(new List.fromJson(v)); });
        }
        if (json['table'] != null) {
            table = <List>[];
            json['table'].forEach((v) { table.add(new List.fromJson(v)); });
        }
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['status'] = this.status;
        if (this.note != null) {
      data['note'] = this.note.map((v) => v.toJson()).toList();
    }
        if (this.table != null) {
      data['table'] = this.table.map((v) => v.toJson()).toList();
    }
        return data;
    }
}

“List”类没有名为“fromJson”的构造函数。 尝试调用不同的构造函数,或定义一个名为“fromJson”的构造函数。 / List.fromJson 和 v.toJson 出错

【问题讨论】:

    标签: json flutter flutter-getx flutter-http


    【解决方案1】:

    错误消息说得很简单。

    你不能打电话

    new List.fromJson(v)
    

    尝试从您的 json 创建一个 dart Iterable 并使用 .from() 构造函数

    List<E>.from(
    Iterable elements,
    {bool growable = true}
    )
    

    或者尝试List类https://api.dart.dev/stable/2.14.2/dart-core/List-class.html定义的其他构造函数

    这个库也可能有帮助 https://pub.dev/packages/json_serializable

    【讨论】:

      【解决方案2】:

      列表是一个抽象类。它没有构造函数fromJson。如果要从 JSON 转换为列表,则必须使用 Elements (Note) 分配一个列表,例如:

      //Generic form 
      List<E>
      // For note 
      List<Note> note;
      // call like that
      json['note'].forEach((v) { note.add(new Note.fromJson(v)); });
      

      模型类注:

      class Note {
        String title;
        String description;
      
        Note({this.title, this.description});
      
        Note.fromJson(Map<String, dynamic> json) {
          title = json['title'];
          description = json['description'];
        }
      
        Map<String, dynamic> toJson() {
          final Map<String, dynamic> data = new Map<String, dynamic>();
          data['title'] = this.title;
          data['description'] = this.description;
          return data;
        }
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 2014-03-12
        • 1970-01-01
        • 2012-06-22
        • 2014-08-01
        相关资源
        最近更新 更多