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

时间:2019-01-07 15:11:11

标签: dart factory

我正在使用以下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对象的列表。但是我遇到了一些编译器错误:

  • 此函数的返回类型为“列表”,但不以return语句结尾。dart(missing_return)
  • 已经定义了默认构造函数。dart(duplicate_constructor_default)
  • 构造函数不能具有类型参数。dart(type_parameter_on_constructor)

知道发生了什么吗?

1 个答案:

答案 0 :(得分:1)

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

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

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

相关问题