How to set all data of List<bool> to be false with some function

Anyone know how to set all data of List<bool> to be false? Here is example:

List<bool> data = [true, false, true];

data = [false, false, false];
// output data = [false, false, false]

and there is my code to convert it, and i know that we can do with looping. But here, i want to do with some function, which is i was tried with data.every((element) => element = false); but, that is not working.

Thanks in advance

Upvotes: 2

Views: 8010

Answers (4)

KuKu
KuKu

Reputation: 7492

Here is my three suggestions.

  • reassign all false List
  • loop each item and set to false
  • use forEach

enter image description here

void main() {
  List<bool> data = [true, false, true];

  print('first origin data: $data');
  data = List<bool>.filled( data.length, false);
  print('first origin data: $data\n');
  
  
  data = [true, false, true];
  print('second origin data: $data');
  for (var loop = 0 ; loop < data.length ; loop++) {
    data[loop] = false;
  }
  print('second modified data: $data\n');
  
  data = [true, false, true];
  print('third origin data: $data');
  data.asMap().forEach((index, value) {
    if (value == true) {
      data[index] = false;
    }
  });
  print('third modified data: $data\n');
  
}


Upvotes: 1

Pritam
Pritam

Reputation: 41

Take a look at fillRange method for list Here is the code you want: data.fillRange(0, data.length, false);

Upvotes: 3

h8moss
h8moss

Reputation: 5020

There are many ways to do something like this, here are a couple of them:

First, use the map method:

data = data.map<bool>((v) => false).toList();

The map method transforms every item on a list, we are using it like you wanted to use every

Second, use the filled method:

data = List.filled(data.length, false, growable: true);

The filled method makes a new list given a length and a value, in our case the length is the previous list length and the value is false.

Upvotes: 8

nvoigt
nvoigt

Reputation: 77304

If you want to keep the data variable the same, you could do this:

void main() {
  List<bool> data = [true, false, true];
  
  data.replaceRange(0, data.length, data.map((element) => false));
  
  print(data);
}

Upvotes: 2

Related Questions