Flutter _TypeError(类型'列表 '不是'Map'类型的子类型 “)

问题描述 投票:1回答:1

我是新手扑动并且出现类型错误。我正在尝试使用json自动序列化。

在这里做了一些事情后,它看起来如何

enter image description here

以下是我试图从api获取数据的方法

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

我的BaseResponse课程看起来像这样

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

有谁可以帮我这个。我被困在这里。一直尝试不同的方法但没有工作。谢谢。

dart flutter
1个回答
0
投票

它看起来像data是一个List<dynamic>,然后data.map(someFunc).toList()将把每个数据元素传递给someFunc并将其形成一个返回类型的someFunc列表(你可能想要成为BaseResponse)。这告诉你,someFunc需要是一个功能,需要dynamic并返回BaseResponse

你想写这样的东西:

  final data = json.decode(res.body);
  List<BaseResponse> responses =
      data.map((j) => BaseResponse.fromJson(j)).toList();
© www.soinside.com 2019 - 2024. All rights reserved.