chopper icon indicating copy to clipboard operation
chopper copied to clipboard

`response.body` not begin casted to right List<Object>

Open Errichamonda opened this issue 4 years ago • 2 comments

Service:

part 'places_service.chopper.dart';

@ChopperApi(baseUrl: '/places')
abstract class PlacesService extends ChopperService {
  static PlacesService create([ChopperClient? client]) =>
      _$PlacesService(client);

  @Get(path: "/")
  Future<Response<List<Place>>> getPlaces();

  @Get(path: "/{slug}")
  Future<Response<Place>> getPlace(@Path('slug') String slug);
}

When I call getPlaces(), response.body is of type CastList and not List<Place> and when I do List<Place> places = response.body I get and error saying type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Place' in type cast

The response from the api looks like this

[
    {
        "slug": "1a1b1c",
        "name": "City1",
        "province": "Province1",
        "province_short": "",
        "cap": "",
        "area": "AB",
        "type": 2,
        "time": 20
    },
    {
        "slug": "2a2b2c",
        "name": "City2",
        "province": "Province1",
        "province_short": "",
        "cap": "",
        "area": "AC",
        "type": 2,
        "time": 30
    }
]

The ChopperClient looks like this

ChopperClient(
    baseUrl: Endpoints.baseApi,
    services: [
      TasksService.create(),
      AuthService.create(),
      PlacesService.create(),
    ],
    interceptors: [
      const HeadersInterceptor(
          {"Content-Type": "application/x-www-form-urlencoded "}),
    ],
    converter: const JsonConverter(),
    errorConverter: const JsonConverter(),
    authenticator: AuthenticatorService(),
  )

Am I missing something?

Errichamonda avatar Jan 13 '22 11:01 Errichamonda

Hmm, what is your Place model? Are u using BultiValue?

JEuler avatar Jan 22 '22 09:01 JEuler

import 'package:app/models/point.dart';
import 'package:hive/hive.dart';
import 'package:json_annotation/json_annotation.dart';

part 'place.g.dart';

@JsonSerializable()
@HiveType(typeId: 1)
class Place {
  @HiveField(0)
  final String slug;
  @HiveField(1)
  final String name;
  @HiveField(2)
  final String province;
  @JsonKey(name: 'province_short')
  @HiveField(3)
  final String provinceShort;
  @HiveField(4)
  final String cap;
  final String? area;
  final int type;
  final int time;
  final List<Point> points;

  Place({
    required this.slug,
    required this.name,
    required this.province,
    required this.provinceShort,
    required this.cap,
    this.area,
    this.type = 0,
    this.time = 0,
    this.points = const [],
  });
  
  factory Place.fromJson(Map<String, dynamic> json) => _$PlaceFromJson(json);
  Map<String, dynamic> toJson() => _$PlaceToJson(this);
}

I'm using JsonSerializable

Errichamonda avatar Jan 24 '22 07:01 Errichamonda

@Errichamonda you need to configure your own JsonConverter.

Take a look here

techouse avatar Mar 11 '23 21:03 techouse