Here is an example on how to do it. I have made title or category nullable since we don't always has this two fields:
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
}
keydoes returnnull(by e.g. make the field a nullable).SearchedUser.fromJson(dynamic response) { return SearchedUser( userId: response['id'], name: response['names'], userName: response['users_name'], profileImage: response['avt'], title: response['title'], category: response['category'], ); }Can you please show me an example how can I handle thenullcheck forkey?title: response['title'] ?? 'default title', category: response['category'] ?? 'default category',