How to use JsonConverter for list in Flutter

Viewed 674

I have a problem with custom Json Converter for Chopper in Flutter. I wrote a code in such a way.


@ChopperApi(baseUrl: '/')
abstract class ChallengeApiService extends ChopperService {
  @Post()
  Future<Response<List<Challenge>>> getChallenges(
    @Body() Map<String, dynamic> body,
  );

  static ChallengeApiService create() {
    final client = ChopperClient(
      interceptors: [DataInterceptor()],
      baseUrl: Config.api_url,
      services: [_$ChallengeApiService()],
      converter: JsonToTypeConverter(
          {Challenge: (jsonData) => Challenge.fromJson(jsonData['data'])}),
    );
    return _$ChallengeApiService(client);
  }
}

And my Converter file is

import 'dart:convert';

import 'package:chopper/chopper.dart';

class JsonToTypeConverter extends JsonConverter {
  final Map<Type, Function> typeToJsonFactoryMap;

  JsonToTypeConverter(this.typeToJsonFactoryMap);

  @override
  Response<BodyType> convertResponse<BodyType, InnerType>(Response response) {
    final Response dynamicResponse = super.convertResponse(response);
    return response.copyWith(
      body: fromJsonData<BodyType, InnerType>(
          dynamicResponse.bodyString, typeToJsonFactoryMap[InnerType]!),
    );
  }

  T fromJsonData<T, InnerType>(String jsonData, Function jsonParser) {
    var jsonMap = json.decode(jsonData);

    if (jsonMap is List) {
      return jsonMap
          .map((item) => jsonParser(item as Map<String, dynamic>) as InnerType)
          .toList() as T;
    }

    return jsonParser(jsonMap);
  }
}

The error is : _TypeError (type 'List' is not a subtype of type 'Map<String, dynamic>')

I know the problem is receiving list from api, but don't know for which reason the list check in converter is not working. Is there any solution ? Im very new to serialisers in flutter. Thank you in advance for any help.

I have solution for now but I know its not correct with this changes in Api service it works:

JsonToTypeConverter({
        Challenge: (json) => json['data'] is List
            ? List<Challenge>.from(
                json['data'].map((model) => Challenge.fromJson(model)))
            : Challenge.fromJson(json['data'])
      }),
0 Answers
Related