KarimHachicha
KarimHachicha

Reputation: 181

Append value of type List to a map

I have a class of type Produit

class Produit {
 String? nom;
 double? prix;
 int? quantite;
 Produit({this.nom, this.prix, this.quantite});
}

I have a List of type Produit

List<Produit> listeProduits = [
.
. 
.
 ]

and i have this map

Map<int, List<Produit>> listePanier = {};

I'm trying to append a new value of type Produit to this map each time a button is pressed .

Upvotes: 0

Views: 912

Answers (1)

julemand101
julemand101

Reputation: 31299

You can do something like this using the update method on Map to make so we handle situations where the key are already in the list (where we then want to append to the existing list) and where the key is missing (where we then want to create a new list with out element):

void main() {
  final Map<int, List<String>> myMap = {
    1: ['String1', 'String2']
  };

  print(myMap);
  // {1: [String1, String2]}

  String newValueToList = 'NewString3';

  // Example of what happens in case the key already exist
  myMap.update(1, (list) => list..add(newValueToList),
      ifAbsent: () => [newValueToList]);

  print(myMap);
  // {1: [String1, String2, NewString3]}

  newValueToList = 'NewString4';

  // Example of what happens if the key does not already exist. In this case
  // we create a new list with the new item
  myMap.update(2, (list) => list..add(newValueToList),
      ifAbsent: () => [newValueToList]);

  print(myMap);
  // {1: [String1, String2, NewString3], 2: [NewString4]}
}

We can also create an extension to help us doing this:

void main() {
  final Map<int, List<String>> myMap = {
    1: ['String1', 'String2']
  };

  print(myMap);
  // {1: [String1, String2]}

  myMap.appendToList(1, 'NewString3');

  print(myMap);
  // {1: [String1, String2, NewString3]}

  myMap.appendToList(2, 'NewString4');

  print(myMap);
  // {1: [String1, String2, NewString3], 2: [NewString4]}
}

extension AppendToListOnMapWithListsExtension<K, V> on Map<K, List<V>> {
  void appendToList(K key, V value) =>
      update(key, (list) => list..add(value), ifAbsent: () => [value]);
}

Upvotes: 2

Related Questions