import 'dart:convert';
const jsonString = '''
[
{
"names": "Jean lewis Mbayabu ",
"users_name": "jeanlewis",
"avt": "Image URL",
"id": "32",
"title": "Canada",
"category": "student"
},
{
"names": "Abhi Vish",
"users_name": "abhi",
"avt": "Image URL",
"id": "59",
"category": "student"
},
{
"names": "Julie Mabengi",
"users_name": "julie",
"avt": "Image URL",
"id": "116"
}
]
''';
class SearchedUser {
final String names;
final String users_name;
final String avt;
final int id;
final String? title;
final String? category;
const SearchedUser(
{required this.names,
required this.users_name,
required this.avt,
required this.id,
required this.title,
required this.category});
factory SearchedUser.fromJson(Map<String, dynamic> json) => SearchedUser(
names: json['names'] as String,
users_name: json['users_name'] as String,
avt: json['avt'] as String,
id: int.parse(json['id'] as String),
title: json['title'] as String?,
// title: json['title'] ?? "defaultTitle", // default title if field is absent or null
category: json['category'] as String?);
// category: json['category'] ?? "defaultCategory"); // default category if field is absent or null
@override
String toString() => 'names: $names, '
'users_name: $users_name, '
'avt: $avt, '
'id: $id, '
'title: $title, '
'category: $category';
}
void main() {
final jsonList = jsonDecode(jsonString) as List<dynamic>;
final searchedUsers = [
for (final map in jsonList.cast<Map<String, dynamic>>())
SearchedUser.fromJson(map)
];
searchedUsers.forEach(print);
// names: Jean lewis Mbayabu , users_name: jeanlewis, avt: Image URL, id: 32, title: Canada, category: student
// names: Abhi Vish, users_name: abhi, avt: Image URL, id: 59, title: null, category: student
// names: Julie Mabengi, users_name: julie, avt: Image URL, id: 116, title: null, category: null
}