dart 桩号不是类型的子类型

kpbwa7wx  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(133)

由于某种原因,在我的Flutter应用程序我得到以下错误消息。
“type '(Stations)=〉Stations'不是'transform'的类型'(String,dynamic)=〉MapEntry〈dynamic,dynamic〉'的子类型”

Future<Stations?> getStationData(int playerId) async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('jwtToken');
const String path = 'Station/GetFirstPlayerStationTopScore';

final uri = Uri.parse('$url/api/$path');

final Map<String, String> queryParams = {
  'playerId': '25801',
  'type': '11',
};
final Uri uriWithParams = uri.replace(queryParameters: queryParams);

try {
  Response res = await get(uriWithParams, headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    // 'Authorization': 'Bearer $token',
  });

  if (res.statusCode == 200) {
    var body = jsonDecode(res.body);
    print(body);
    if (body != null) {
      return body.map((Stations item) =>
          Stations.fromJson(item as Map<String, Stations>));
    } else {
      return null;
    }
  } else {
    throw Exception('Unable to retrieve posts.');
  }
} catch (e) {
  print(e.toString());
  throw Exception('Unable to retrieve posts.');
}

我是这样称呼上面的

HttpService api = HttpService();

void getData() async {
  int playerId = 25801; // Or whatever playerId you want to use
  stations = await api.getStationData(playerId);
}

球员存在的确定,但不知道我做错了什么,在我的模型。我只是在测试这个,所以不是所有的变量都被填满了。

@JsonSerializable()
class Stations {
  final int? id;
  final int? stationId;
  final String? decimalName1;
  final String? decimalName2;
  final String? playerName;

  final int? decimalValue1;

  Stations(
      {this.id,
      this.stationId,
      this.decimalName1,
      this.decimalValue1,
      this.decimalName2,
      this.playerName});

  factory Stations.fromJson(Map<String, dynamic> json) {
    return Stations(
      decimalValue1: json['decimalValue1'],
      playerName: json['playerName'],
    );
  }

  Map<String, dynamic> toJson() => {
        'decimalValue1': decimalValue1,
        'playerName': playerName,
      };
}

我得到的错误是

"type '(Stations) => Stations' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'"

我真的是新的Flutter来自一个c尖锐的背景,所以裸露与我,如果这是简单的东西?

lfapxunr

lfapxunr1#

我认为这里有两个错误。第一个是写一个

return body.map((Stations item) =>

这应该是

return body.map((item) =>

因为该参数还不是Stations
但这其实不是主要问题。map用于对象是某种类型的列表。但我相信一定是单个的Stations。我相信

return body.map((Stations item) =>
      Stations.fromJson(item as Map<String, Stations>));

需要简单地替换为

return Stations.fromJson(body);

如果不是这种情况,请分享您的答复,以便我们判断可能出现的问题

相关问题