Dart Future.doWhile()
Syntax & Examples

Future.doWhile() static-method

The `doWhile` static method in Dart performs an operation repeatedly until it returns false.


Syntax of Future.doWhile()

The syntax of Future.doWhile() static-method is:

 Future doWhile(FutureOr<bool> action()) 

This doWhile() static-method of Future performs an operation repeatedly until it returns false.

Parameters

ParameterOptional/RequiredDescription
actionrequiredA function representing the operation to be performed. This function should return a boolean value indicating whether to continue the loop or not.

Return Type

Future.doWhile() returns value of type Future.



✐ Examples

1 Counting from 1 to 5

In this example,

  1. We initialize a variable count to 0.
  2. We call the doWhile static method with a function representing the operation to be performed.
  3. The function increments count, prints its value, and returns true until count is less than 5.
  4. The loop stops when the condition count < 5 becomes false.

Dart Program

void main() {
  int count = 0;
  Future.doWhile(() {
    count++;
    print('Count: $count');
    return count < 5;
  });
}

Output

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

2 Decreasing balance by 10 until it's positive

In this example,

  1. We initialize a variable balance to 100.0.
  2. We call the doWhile static method with a function representing the operation to be performed.
  3. The function decreases balance by 10.0, prints its value, and returns true until balance is greater than 0.0.
  4. The loop stops when the condition balance > 0.0 becomes false.

Dart Program

void main() {
  double balance = 100.0;
  Future.doWhile(() {
    balance -= 10.0;
    print('Balance: $balance');
    return balance > 0.0;
  });
}

Output

Balance: 90.0
Balance: 80.0
Balance: 70.0
Balance: 60.0
Balance: 50.0
Balance: 40.0
Balance: 30.0
Balance: 20.0
Balance: 10.0
Balance: 0.0

3 Removing numbers from a list until it's empty

In this example,

  1. We create a list of integers numbers.
  2. We call the doWhile static method with a function representing the operation to be performed.
  3. The function removes the first element from the list, prints the list, and returns true until the list is not empty.
  4. The loop stops when the list becomes empty.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  Future.doWhile(() {
    numbers.removeAt(0);
    print('Numbers: $numbers');
    return numbers.isNotEmpty;
  });
}

Output

Numbers: [2, 3, 4, 5]
Numbers: [3, 4, 5]
Numbers: [4, 5]
Numbers: [5]
Numbers: []

Summary

In this Dart tutorial, we learned about doWhile() static-method of Future: the syntax and few working examples with output and detailed explanation for each example.