3
votes

I am new to flutter and getting type error. I am trying to use json automated serializations.

AFTER DOING SOME TWEAKS HERE IS HOW IT LOOKS LIKE

enter image description here

Here is how I am trying to get the data from api

  Future getMyProduct() async {
     final res = await http.get('url');
     final data = json.decode(res.body);
     BaseResponse req = new BaseResponse.fromJson(data);
     return req;
  }

My BaseResponse class looks like this

import 'package:dynamicapp/model/model.dart';
import 'package:json_annotation/json_annotation.dart';

part 'response.g.dart';

@JsonSerializable()
class BaseResponse extends Object {
    final int id;

final int sellingPrice;
final int totalStock;
final String productName;
final String productDesc;
final List<Image> images;

BaseResponse(this.id, this.sellingPrice, this.totalStock, this.productName,
    this.productDesc, this.images);

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

Map<String, dynamic> toJson() => _$BaseResponseToJson(this);
}

@JsonSerializable()
 class Image extends Object {
    final int id;
    final String image;
//  final int product_id;

   Image(this.id, this.image);
factory Image.fromJson(Map<String, dynamic> json) => _$ImageFromJson(json);
   Map<String, dynamic> toJson() => _$ImageToJson(this);
}

Could anyone please help me with this. I am stuck here. Have been trying different methods but none working. Thank you.

1
change json.decode to jsonDecode . Look this: flutter.dev/docs/development/data-and-backend/json - Rubens Melo
It gives same error. I followed exactly like documentations. Still same error - Hkm Sadek
try change final data to final Map data to explicit the return type of jsonDecode - Rubens Melo
It gives the same error final Map data = jsonDecode(res.body); var p = BaseResponse.fromJson(data); How can I convert the BaseResponse.fromJson(data) into a list instead of a map? - Hkm Sadek
OK I got the problem. It returns an array of items and in the BaseResponse call I have Object. So if I write BaseResponse.fromJson(jsonresponse[0]); it works with 0 index. But how can I make a list of array? - Hkm Sadek

1 Answers

1
votes

It looks like data is a List<dynamic>, then data.map(someFunc).toList() will take each element of data pass it to someFunc and form it back into a list of the return type of someFunc (which you will presumably want to be BaseResponse). Which tells you that someFunc needs to be a function that takes dynamic and returns BaseResponse.

You'd want to write something like this:

  final data = json.decode(res.body);
  List<BaseResponse> responses =
      data.map((j) => BaseResponse.fromJson(j)).toList();