I'm having trouble consuming an API. I can save data to the database, but the following error occurs:
_TypeError (type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'action')
This is a part of my repository.
Future<MyModel?> test() async {
.
.
var headerParameters = {
"teanantId": tenantId,
"Authorization": headerAuth,
};
var queryParameters = {
'deviceId': appController.deviceId,
};
try {
Response response = await dio.post(
BASE_URL methodPost,
data: jsonEncode(queryParameters),
options: Options(
headers: headerParameters,
contentType: 'application/json',
responseType: ResponseType.json),
);
if (response.statusCode == 200) {
var saida = MyModel.fromJson(json.decode(response.data));
return saida;
}
} on DioError catch (exc) {
throw ('Exception ${exc.message}');
}
return null;
}
Here's my model.
class MyModel {
List<Data?>? data;
bool? success;
int? statusCode;
String? message;
.
.
MyModel.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = <Data>[];
json['data'].forEach((v) {
data!.add(new Data.fromJson(v));
});
}
success = json['success'];
statusCode = json['statusCode'];
message = json['message'];
}
.
.
.
class Data {
String? id;
String? type;
User? user;
String? value;
String? status;
// List<Null>? errors;
String? createdAt;
// Null? verificationCode;
// Null? crossValidationIdentifier;
Data({
this.id,
this.type,
this.user,
this.value,
this.status,
this.createdAt,
});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
type = json['type'];
user = json['user'] != null ? new User.fromJson(json['user']) : null;
value = json['value'];
status = json['status'];
createdAt = json['createdAt'];
}
How can I get past this error? The error occurs in foreach.
CodePudding user response:
just decode the response.data
to Map<String,dynamic>
import 'dart:convert';
....
final post = MyModel.fromJson(json.decode(response.data));
return post;
if your data is not list of map, then you just need to convert it from json.
Data? data;
...
MyModel.fromJson(Map<String, dynamic> json) {
data = Data.fromJson(json.decode(json["data"]));
success = json['success'];
statusCode = json['statusCode'];
message = json['message'];
}
this will work if your data from api is a Map, not list of map.