Home > front end >  How to add a map into List of maps?
How to add a map into List of maps?

Time:01-24

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.

CodePudding user response:

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);

CodePudding user response:

  
// 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);
  • Related