gpt4 book ai didi

dart - 构造函数不能具有类型参数。dart(type_parameter_on_constructor)

转载 作者:行者123 更新时间:2023-12-03 03:41:53 30 4
gpt4 key购买 nike

我正在使用以下dart包(json_annotation,json_serializable,build_runner)根据此page序列化/反序列化json。

这是我的代码:

import 'package:json_annotation/json_annotation.dart';

part 'car_type.g.dart';

@JsonSerializable()
class CarType {

final int id;

@JsonKey(name: 'type_label')
final String label;

final String description;

CarType(this.id, this.label, this.description);

factory CarType.fromJson(Map<String, dynamic> json) =>
_$CarTypeFromJson(json);

factory List<CarType> CarType.fromJsonList(dynamic jsonArray){
final list = jsonArray as List;
final carTypesList = list.map((i) => CarType.fromJson(i));
return carTypesList;
}
}

因此,我想使用 factory List<CarType> CarType.fromJsonList(dynamic jsonArray)传递一个json数组以获取CarType对象的列表。但是我遇到了一些编译器错误:
  • 此函数的返回类型为'List',但不以return语句结尾。dart(missing_return)
  • 默认的构造函数已经定义。dart(duplicate_constructor_default)
  • 构造函数不能具有类型参数。dart(type_parameter_on_constructor)

  • 知道发生了什么吗?

    最佳答案

    factory List<CarType> CarType.fromJsonList(dynamic jsonArray){

    您不能为构造函数指定返回类型。
    返回类型始终与构造函数所属的类相同。

    只需将 factory替换为 static,就可以了,
    除了 json_serializable需要工厂构造函数,然后您需要删除返回类型并找到另一种方法来获取 List

    关于dart - 构造函数不能具有类型参数。dart(type_parameter_on_constructor),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54076969/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com