skip to Main Content

I am learning list and here i have created a simple demo for traversing all numbers of list using map…

according to me it should print ‘okay’ 9 times as i have nine integer inside a list
and another new thing is that if i print this list named x after this line of code..it works which i have commented.

final List<int>  numbers=[10,20,30,40,50,60,70,80,90];

final x=numbers.where((element) {
  print('Okay');
  return element>50;
});

// if i print x it will show hello
print(x);

2

Answers


  1. void main() {
    final List numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90];

    // Using where to filter numbers greater than 50
    final x = numbers.where((element) {
        print('Okay'); // This will execute for each element being checked
        return element > 50;
    });
    
    // Force evaluation by converting to a list
    final filteredNumbers = x.toList(); 
    
    // Print the filtered numbers
    print(filteredNumbers); // Will show: [60, 70, 80, 90]
    

    }

    his code is a straightforward demonstration of filtering data in Dart using built-in collection methods, showcasing important programming principles applicable across various languages. For further details on Dart’s collection methods and their usage, you can refer to the official Dart documentation.

    Login or Signup to reply.
  2. [ where ] method in Dart returns a lazy iterable
    Okay only executed when you start iterating over x

    final List<int> numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90];
    
    final x = numbers.where((element) {
      print('Okay');
      return element > 50;
    }).toList(); // Convert the iterable to a List
    
    print(x); // This will print [60, 70, 80, 90]
    

    toList() method forces the iteration of the [where] clause which causing the print(‘Okay’) statement to execute 9 times.

    Hope it will help

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search