我正面临一个问题,当数据从api提取,不映射到模型,并抛出以下错误,我还发布了BodyModel类,其中包含fromJson
函数:
Future<BodyModel> fetchJson(http.Client client, String? id) async {
final response = await client.get(
Uri.parse(uri2),
);
if (response.statusCode == 200) {
String jsonData = response.body;
print(response.body);
//print(jsonEncode(response.body));
BodyModel alpha = responseJSON(jsonData);
//print(alpha.toSet());
//bravo = alpha;
return alpha;
} else {
throw Exception('We were not able to successfully download the json data.');
}
}
BodyModel responseJSON(String response) {
final parse = jsonDecode(response);
print(parse.toString());
final resp = parse<BodyModel>((json) => BodyModel.fromJson(json));
print(resp);
return resp;
}
import 'package:flutter/material.dart';
class BodyModel {
String body;
String title;
BodyModel({
required this.body,
required this.title,
});
factory BodyModel.fromJson(Map<String, dynamic> jsonData) {
return BodyModel(
body: jsonData['body'].toString(),
title: jsonData['title'].toString(),
);
}
}
您正在呼叫parse<BodyModel>(...)
。不清楚你认为它应该做什么,但是parse
是一个包含Map<String, dynamic>
的变量,而不是一个通用函数。它的类型是dynamic
,所以当你误用它时不会得到任何警告。考虑将parse声明为
Map<String, dynamic> parse = jsonDecode(response);
所以它有正确的类型
从responseJSON
的返回类型,我猜你想做:
final resp = BodyModel.fromJson(parse);