I am facing an issue when data is fetched from the api and is not mapped into the model and the following error is thrown I have also posted the BodyModel class which contains the fromJson
function:
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(),
);
}
}
CodePudding user response:
You are calling parse<BodyModel>(...)
.
It's not clear what you think that's supposed to do, but parse
is a variable containing a Map<String, dynamic>
, not a generic function.
It has type dynamic
, so you won't get any warnings when misusing it.
Consider declaring parse as
Map<String, dynamic> parse = jsonDecode(response);
so it has the correct type.
From the return type of responseJSON
, my guess is that you want to do:
final resp = BodyModel.fromJson(parse);