Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors can't have type parameters.dart(type_parameter_on_constructor)

Tags:

factory

dart

I am using the following dart packages (json_annotation, json_serializable, build_runner) to serialize/de-serialize json according to this page.

This is my code:

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

So with the factory List<CarType> CarType.fromJsonList(dynamic jsonArray) I want to pass a json array to get back a list of CarType objects. However I'am getting a couple of compiler errors namely:

  • This function has a return type of 'List', but doesn't end with a return statement.dart(missing_return)
  • The default constructor is already defined.dart(duplicate_constructor_default)
  • Constructors can't have type parameters.dart(type_parameter_on_constructor)

Any idea what is going on?

like image 998
unbalanced_equation Avatar asked Mar 17 '26 22:03

unbalanced_equation


1 Answers

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

You can't specify a return type for a constructor.
The return type is always the same as the class the constructor is member of.

Just replace factory with static and you should be fine, except json_serializable expects a factory constructor, then you need to remove the return type and find another approach to get the List.

like image 67
Günter Zöchbauer Avatar answered Mar 21 '26 02:03

Günter Zöchbauer