How can I get information from this code Jason I don't know what the problem is? I tried to get the total at the end of Jason's code and the information inside the data, but it shows me this error.
the error
GetLogsData error is: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'
here is the jonData i wanna get data and total from logs object
{
"logs": {
"data": [
{
"description": "Failed Login Attempt",
"created_at": "2022-07-21T13:58:49.000000Z"
}
],
"total": 21
},
"totalLogs": 21
}
here is the code:
in here getting the logs
Future GetLogsData() async {
try {
var response = await CallApi().getData('logs');
jsonResponse = json.decode(response.body);
List<_LogsList> Logs_List = [];
for (var index in jsonResponse) {
_LogsList logsList = _LogsList(
data: index['data'] ?? '',
total: index['total'] ?? '',
);
Logs_List.add(logsList);
}
return Logs_List;
}catch (e) {
print('GetLogsData error is: $e');
return[];
}
}
this is storeing list
class _LogsList {
final dynamic total;
final List<Map<String, dynamic>> data;
_LogsList( {this.total, this.data, });
}
CodePudding user response:
I think your json has extra coma in it. It should have to look like this.
{
"logs": {
"data": [
{
"description": "Failed Login Attempt",
"created_at": "2022-07-21T13:58:49.000000Z"
}
],
"total": 21
},
"totalLogs": 21
}
CodePudding user response:
In my opinion, you should first create a Log
class with ` factory method, this way you'll be able to easily generate a list of logs. Follow these steps,
Step 1 : Create a Log
class
class Log {
final String description, createdAt;
const Log({
required this.description,
required this.createdAt,
});
factory Log.fromData(Map<String, dynamic> data) {
return Log(
description: data['description'],
createdAt: data['created_at'],
);
}
}
Step 2 : Decode the response and convert it to a list of logs
final data = json.decode(response.body);
final List<Log> logs = data['logs']['data']
.map<Log>((logData) => Log.fromData(logData))
.toList();
After this, based on your code, you can choose to create an extra LogList
class or can directly extract total number of logs, but the base should be this, Good luck!