Home > Net >  Is there a way to check the value of previous value in iteration? dart
Is there a way to check the value of previous value in iteration? dart

Time:01-27

In the below code ,variable modelMap returns a map and I am iterating through that

var modelMap = parsedJson.values;

modelMap.forEach((element) {

    modelName = element["ModelName"];
  
    modelList.add(modelName) ;
  
});

Here I have to check if the previous iteration's element has a particular value and do my operations based on that.. for example if the pervious iteration has brandName equal to my current iteration's brandname then I will add the current model to the list.. if they are not equal I have to skip...Is it possible to do that?

CodePudding user response:

You can just use some variable to save the previous. And compare to that. Here is an example where you don't take it if it is the same brandName:

List result = [];

final list = [
  {'brandName': 1},
  {'brandName': 2},
  {'brandName': 2},
  {'brandName': 3},
  {'brandName': 3},
  {'brandName': 3},
  {'brandName': 5},
  {'brandName': 3},
  {'brandName': 1},
  {'brandName': 1},
  {'brandName': 6}
];
dynamic previous;

list.forEach((element) {
  if (previous?['brandName'] != element['brandName']) {
    result.add(element);
  }
  previous = element;
});

print(result);
//[{brandName: 1}, {brandName: 2}, {brandName: 3}, {brandName: 5}, {brandName: 3}, {brandName: 1}, {brandName: 6}]
  • Related