Reputation: 1489
Let's say i have this List of maps :
List values = [
{
'icon': FontAwesomeIcons.book,
'title': 'A',
'books': [
{'author': 'Max', 'age': 30},
{'author': 'Dani', 'age': 45}
]
},
{
'icon': FontAwesomeIcons.book,
'title': 'B',
'books': [],
}
];
How to check if this book exists to where the title 'A' {'author': 'Steve', 'age': 28},
and if it doesn't exists how to add it.
Edit:
The result i want to reach is :
List values = [
{
'icon': FontAwesomeIcons.book,
'title': 'A',
'books': [
{'author': 'Max', 'age': 30},
{'author': 'Dani', 'age': 45},
{'author': 'Steve', 'age': 28}
]
},
{
'icon': FontAwesomeIcons.book,
'title': 'B',
'books': [],
}
];
Upvotes: 0
Views: 109
Reputation: 106
I strongly recommend using Data Models. it will make your work easier.
class DataModel {
String? title;
List<Books>? books;
DataModel({this.title, this.books});
DataModel.fromJson(Map<String, dynamic> json) {
title = json['title'];
if (json['books'] != null) {
books = <Books>[];
json['books'].forEach((v) {
books!.add(new Books.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['title'] = this.title;
if (this.books != null) {
data['books'] = this.books!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Books {
String? author;
int? age;
Books({this.author, this.age});
Books.fromJson(Map<String, dynamic> json) {
author = json['author'];
age = json['age'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['author'] = this.author;
data['age'] = this.age;
return data;
}
}
When using this model, you can easily convert and edit your data:
List<DataModel> list = [];
for(final item in values){
list.add(DataModel.fromJson(item));
}
final bookExcists = list.any((book) => book.title == 'A');
if(bookExcists){
list.firstWhere((book) => book.title == 'A').books?.add(Books.fromJson({'author': 'Steve', 'age': 28}));
}
for(final item in list){
print(item.toJson());
}
Upvotes: 1
Reputation: 106
// Check by title
final bookExcists = values.any((book) => book['title'] == 'A');
if(!bookExcists){
values.add({
'icon': FontAwesomeIcons.book,
'title': 'A',
'books': [
{'author': 'Max', 'age': 30},
{'author': 'Dani', 'age': 45}
]
});
}
print(values);
Upvotes: 0
Reputation: 63779
You can use .firstWhere
to find item, like
final result = values.firstWhere(
(element) => element["title"] == "A",
orElse: () => null,
);
print(result);
if (result == null) {
values.add({
'icon': FontAwesomeIcons.book,
'title': 'A',
'books': [
{'author': 'Max', 'age': 30},
{'author': 'Dani', 'age': 45}
]
});
}
print(values);
Upvotes: 1