Kinda Code
Home/Dart/Flutter & Dart: every() method examples

Flutter & Dart: every() method examples

Last updated: February 06, 2023

A few examples of using the every() method (of the Iterable class) in Dart (and Flutter as well). The purpose of this method is to check if every element of a given iterable satisfies one or multiple conditions (with a test function):

bool every(
   bool test(
     E element
   )
)

Check whether every number in a list is exactly divisible by 3

The code:

void main() {
  var myList = [0, 3, 6, 9, 18, 21, 81, 120];
  bool result1 = myList.every((element){
    if(element %3 ==0){
      return true;
    } else {
      return false; 
    }
  }); 
  
  // expectation: true
  print(result1); 
}

Output:

true

Check whether every name in the list contains the “m” character

The code:

void main() {
  var names = ['Obama', 'Trump', 'Biden', 'Pompeo']; 
  bool hasM = names.every((element) {
     if(element.contains('m')) return true;
     return false;
  });
  
  print(hasM);
}

Output:

false

You can find more details about the every() method in the official docs.

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Related Articles