Dart Memo : conditional list

Dr_Skele·2023년 1월 2일
0

In a list, its element can be changed via, 'if' statement. It's much easier than adding or removing a element when conditions change.

void main() {
  var addFive = true;
  var myList = [
    'one',
    'two',
    'three',
    'four',
    if(addFive) 'five', //element is added when 'addFive' is true.
  ];
  print(myList); //result : [one, two, three, four, five]
}

Also, there is a way to put another list in a list similar to the way it is above.

void main() {
  var myList = [
    'one',
    'two',
    'three',
    'four',
    'five',
  ];
  var newList = [
    for(var element in myList) element,
    'six',
    'seven',
    'eight',
    'nine',
    'ten'
  ];
  print(newList);
}

Elements can be added from another list by iterating over it using 'for'. If we combine both, list can be merged when we want it to be.

void main() {
  var mergeList = true;
  var myList = [
    'one',
    'two',
    'three',
    'four',
    'five',
  ];
  var newList = [
    if(mergeList) for(var element in myList) element,
    'six',
    'seven',
    'eight',
    'nine',
    'ten'
  ];
  print(newList);
}
profile
Tireless And Restless Debugging In Source : TARDIS

0개의 댓글