Skip to main content

Loops in Dart πŸ’ͺπŸ’ͺπŸ’ͺ😎😎😎

 

    

Loops in Dart   πŸ’ͺπŸ’ͺπŸ’ͺ😎😎😎

Dart Loops

In Programming, loops are used to repeat a block of code until certain conditions are not completed. For, e.g., if you want to print your name 100 times, then rather than typing print(“your name”); 100 times, you can use a loop.

There are different types of loop in Dart. They are:

Info

Note: The primary purpose of all loops is to repeat a block of code.

Let’s first print the name 10 times without using a loop.

void main() {
    print("John Doe");
    print("John Doe");
    print("John Doe");
    print("John Doe");
    print("John Doe");
    print("John Doe");
    print("John Doe");
    print("John Doe");
    print("John Doe");
    print("John Doe");
}

Show Output
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe

We will learn for loop in the next section, paste the code and see the output. It will print your name 10 times.

void main() {
  for (int i = 0; i < 10; i++) {
    print("John Doe");
  }
}

Show Output
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe

 

For Loop in Dart

For Loop

This is the most common type of loop. You can use for loop to run a code block multiple times according to the condition. The syntax of for loop is:

for(initialization; condition; increment/decrement){
            statements;
}
  • Initialization is executed (one time) before the execution of the code block.
  • Condition defines the condition for executing the code block.
  • Increment/Decrement is executed (every time) after the code block has been executed.

Example 1: To Print 1 To 10 Using For Loop

This example prints 1 to 10 using for loop. Here int i = 1; is initialization, i<=10 is condition and i++ is increment/decrement.

void main() {
  for (int i = 1; i <= 10; i++) {
    print(i);
  }
}

Show Output
1
2
3
4
5
6
7
8
9
10

Example 2: To Print 10 To 1 Using For Loop

This example prints 10 to 1 using for loop. Here int i = 10; is initialization, i>=1 is condition and i-- is increment/decrement.

void main() {
  for (int i = 10; i >= 1; i--) {
    print(i);
  }
}

Show Output
10
9
8
7
6
5
4
3
2
1

Example 3: Print Name 10 Times Using For Loop

This example prints the name 10 times using for loop. Based on the condition, the body of the loop executes 10 times.

void main() {
  for (int i = 0; i < 10; i++) {
    print("John Doe");
  }
}

Show Output
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe
John Doe

Example 4: Display Sum of n Natural Numbers Using For Loop

Here, the value of the total is 0 initially. Then, the for loop is iterated from i = 1 to 100. In each iteration, i is added to the total, and the value of i is increased by 1. Result is 1+2+3+….+99+100.

void main(){

  int total = 0;
  int n = 100; // change as per required
  
  for(int i=1; i<=n; i++){
    total = total + i;
  }
  
  print("Total is $total");
  
}

Show Output
Total is 5050

Example 5: Display Even Numbers Between 50 to 100 Using For Loop

This program will print even numbers between 50 to 100 using for loop.

void main(){
  for(int i=50; i<=100; i++){
    if(i%2 == 0){
      print(i);
    }
  } 
}

Show Output
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100

Infinite Loop In Dart

If the condition never becomes false in looping, it is called an infinite loop. It uses more resources on your computer. The task is done repeatedly until the memory runs out.

This program prints 1 to infinite because the condition is i>=1, which is always true with i++.

void main() {
  for (int i = 1; i >= 1; i++) {
    print(i);
  }
}
Info

Note: Infinite loops take your computer resources continuously, use more power, and slow your computer. So always check your loop before use.



 

For Each Loop in Dart

For Each Loop

The for each loop iterates over all list elements or variables. It is useful when you want to loop through list/collection. The syntax of for-each loop is:

collection.forEach(void f(value));

Example1: Print Each Item Of List Using Foreach

This will print each name of football players.

void main(){
  List<String> footballplayers=['Ronaldo','Messi','Neymar','Hazard'];
  footballplayers.forEach( (names)=>print(names));
}

Show Output
Ronaldo
Messi
Neymar
Hazard

Example2: Print Each Total and Average Of Lists

This program will print the total sum of all numbers and also the average value from the total.

void main(){
  List<int> numbers = [1,2,3,4,5];
  
  int total = 0;
  
   numbers.forEach( (num)=>total= total+ num);
  
  print("Total is $total.");
  
  double avg = total / (numbers.length);
  
  print("Average is $avg.");
  
}

Show Output
Total is 15.
Average is 3.

For In Loop In Dart

There is also another for loop, i.e., for in loop. It also makes looping over the list very easily.

void main(){
    List<String> footballplayers=['Ronaldo','Messi','Neymar','Hazard'];

  for(String player in footballplayers){
    print(player);
  }
}

Show Output
Ronaldo
Messi
Neymar
Hazard

How to Find Index Value Of List

In dart, asMap method converts the list to a map where the keys are the index and values are the element at the index.

void main(){

List<String> footballplayers=['Ronaldo','Messi','Neymar','Hazard'];

footballplayers.asMap().forEach((index, value) => print("$value index is $index"));

}

Show Output
Ronaldo index is 0
Messi index is 1
Neymar index is 2
Hazard index is 3

Example: Print Unicode Value of Each Character of String

This will split the name into Unicode values and then find characters from the Unicode value.

void main(){
  
  String name = "John";
     
for(var codePoint in name.runes){
  print("Unicode of ${String.fromCharCode(codePoint)} is $codePoint.");
}
}

Show Output
Unicode of J is 74.
Unicode of o is 111.
Unicode of h is 104.
Unicode of n is 110.

While Loop in Dart

While Loop

In while loop, the loop’s body will run until and unless the condition is true. You must write conditions first before statements. This loop checks conditions on every iteration. If the condition is true, the code inside {} is executed, if the condition is false, then the loop stops.

Syntax

while(condition){  
       //statement(s);  
      // Increment (++) or Decrement (--) Operation;  
}  
  • A while loop evaluates the condition inside the parenthesis ().
  • If the condition is true, the code inside {} is executed.
  • The condition is re-checked until the condition is false.
  • When the condition is false, the loop stops.

Example 1: To Print 1 To 10 Using While Loop

This program prints 1 to 10 using while loop.

void main() {
  int i = 1;
  while (i <= 10) {
    print(i);
    i++;
  }
}

Show Output
1
2
3
4
5
6
7
8
9
10

Info

Note: Do not forget to increase the variable used in the condition. Otherwise, the loop will never end and becomes an infinite loop.

Example 2: To Print 10 To 1 Using While Loop

This program prints 10 to 1 using while loop.

void main() {
  int i = 10;
  while (i >= 1) {
    print(i);
    i--;
  }
}

Show Output
10
9
8
7
6
5
4
3
2
1

Example 3: Display Sum of n Natural Numbers Using While Loop

Here, the value of the total is 0 initially. Then, the while loop is iterated from i = 1 to 100. In each iteration, i is added to the total, and the value of i is increased by 1. Result is 1+2+3+….+99+100.

void main(){

  int total = 0;
  int n = 100; // change as per required
  int i =1;

  while(i<=n){
    total = total + i;
    i++;
  }
  
  print("Total is $total");
  
}

Show Output
Total is 5050

Example 4: Display Even Numbers Between 50 to 100 Using While Loop

This program will print even numbers between 50 to 100 using while loop.

void main(){
  int i = 50;
  while(i<=100){
  if(i%2 == 0){
      print(i);
    }
    i++;
  }
}

Show Output
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100

 

Do While Loop in Dart

Do While Loop

Do while loop is used to run a block of code multiple times. The loop’s body will be executed first, and then the condition is tested. The syntax of do while loop is:

do{
    statement1;
    statement2;
    .
    .
    .
    statementN;
}while(condition);
  • First, it runs statements, and finally, the condition is checked.
  • If the condition is true, the code inside {} is executed.
  • The condition is re-checked until the condition is false.
  • When the condition is false, the loop stops.
Info

Note: In a do-while loop, the statements will be executed at least once time, even if the condition is false. It is because the statement is executed before checking the condition.

Example 1: To Print 1 To 10 Using Do While Loop

void main() {
  int i = 1;
  do {
    print(i);
    i++;
  } while (i <= 10);
}

Show Output
1
2
3
4
5
6
7
8
9
10

Example 2: To Print 10 To 1 Using Do While Loop

void main() {
  int i = 10;
  do {
    print(i);
    i--;
  } while (i >= 1);
}

Show Output
10
9
8
7
6
5
4
3
2
1

Example 3: Display Sum of n Natural Numbers Using Do While Loop

Here, the value of the total is 0 initially. Then, the do-while loop is iterated from i = 1 to 100. In each iteration, i is added to the total, and the value of i is increased by 1. Result is 1+2+3+….+99+100.

void main(){

  int total = 0;
  int n = 100; // change as per required
  int i =1;
  
  do{
  total = total + i;
    i++;
  }while(i<=n);
  
  print("Total is $total");
  
}

Show Output
Total is 5050

When The Condition Is False

Let’s make one condition false and see the demo below. Hello got printed if the condition is false.

void main(){

  int number = 0;
  
  do{
  print("Hello");
  number--;
  }while(number >1);
  
}

Show Output
Hello

  

Break and Continue in Dart

Dart Break and Continue

In this tutorial, you will learn about the break and continue in dart. While working on loops, we need to skip some elements or terminate the loop immediately without checking the condition. In such a situation, you can use the break and continue statement.

Break Statement

Sometimes you will need to break out of the loop immediately without checking the condition. You can do this using break statement.

The break statement is used to exit a loop. It stops the loop immediately, and the program’s control moves outside the loop. Here is syntax of break:

break;

Example 1: Break In Dart For Loop

Here, the loop condition is true until the value of i is less than or equal to 10. However, the break says to go outside the loop when the value of i becomes 5.

void main() {
  for (int i = 1; i <= 10; i++) {
    if (i == 5) {
      break;
    }
    print(i);
  }
}

Example 2: Break In Dart Negative For Loop

Here, the loop condition is true until the value of i is more than or equal to 1. However, the break says to go outside the loop when the value of i becomes 7.

void main() {
  for (int i = 10; i >= 1; i--) {
    if (i == 7) {
      break;
    }
    print(i);
  }
}

Example 3: Break In Dart While Loop

Here, this while loop condition is true until the value of i is less than or equal to 10. However, the break says to go outside the loop when the value of i becomes 5.

void main() {
 int i =1;
 while(i<=10){
  print(i);
   if (i == 5) {
      break;
    }
    i++;
 }
}

Show Output
1
2
3
4
5

Example 4: Break In Switch Case

As we already learn in dart switch case, it is important to add break keyword in switch statement. This example prints the month name based on the number of the month using a switch case.

void main() {
  var noOfMoneth = 5;
  switch (noOfMoneth) {
    case 1:
      print("Selected month is January.");
      break;
    case 2:
      print("Selected month is February.");
      break;
    case 3:
      print("Selected month is march.");
      break;
    case 4:
      print("Selected month is April.");
      break;
    case 5:
      print("Selected month is May.");
      break;
    case 6:
      print("Selected month is June.");
      break;
    case 7:
      print("Selected month is July.");
      break;
    case 8:
      print("Selected month is August.");
      break;
    case 9:
      print("Selected month is September.");
      break;
    case 10:
      print("Selected month is October.");
      break;
    case 11:
      print("Selected month is November.");
      break;
    case 12:
      print("Selected month is December.");
      break;
    default:
      print("Invalid month.");
      break;
  }
}

Show Output
Selected month is May.

Continue Statement

Sometimes you will need to skip an iteration for a specific condition. You can do this utilizing continue statement.

The continue statement skips the current iteration of a loop. It will bypass the statement of the loop. It does not terminate the loop but rather continues with the next iteration. Here is the syntax of continue statement:

continue;

Example 1: Continue In Dart

Here, the loop condition is true until the value of i is less than or equal to 10. However, the continue says to go to the next iteration of the loop when the value of i becomes 5.

void main() {
  for (int i = 1; i <= 10; i++) {
    if (i == 5) {
      continue;
    }
    print(i);
  }
}

Show Output
1
2
3
4
6
7
8
9
10

Example 2: Continue In For Loop Dart

Here, the loop condition is true until the value of i is more than or equal to 1. However, the continue says to go to the next iteration of the loop when the value of i becomes 4.

void main() {
  for (int i = 10; i >= 1; i--) {
    if (i == 4) {
      continue;
    }
    print(i);
  }
}

Show Output
10
9
8
7
6
5
3
2
1

Example 3: Continue In Dart While Loop

Here, this while loop condition is true until the value of i is less than or equal to 10. However, the continue says to go to the next iteration of the loop when the value of i becomes 5.

void main() {
  int i = 1;
  while (i <= 10) {
    if (i == 5) {
      i++;
      continue;
    }
    print(i);
    i++;
  }
}

Show Output
1
2
3
4
6
7
8
9
10

   

Exception Handling in Dart

Exception In Dart

An exception is an error that occurs at runtime during program execution. When the exception occurs, the flow of the program is interrupted, and the program terminates abnormally. There is a high chance of crashing or terminating the program when an exception occurs. Therefore, to save your program from crashing, you need to catch the exception.

Info

Note: If you are attempting a task that might result in an error, it’s a good habit to use the try-catch statement.

Syntax

try {
// Your Code Here
  }
catch(ex){
// Exception here
}

Try & Catch In Dart

Try You can write the logical code that creates exceptions in the try block.

Catch When you are uncertain about what kind of exception a program produces, then a catch block is used. It is written with a try block to catch the general exception.

Example

void main() {   
   int a = 18;   
   int b = 0;   
   int res;    
     
   try {    
      res = a ~/ b;
      print("Result is $res");   
   }    
    // It returns the built-in exception related to the occurring exception  
   catch(ex) {   
      print(ex);   
    }   
}  
Show Output
IntegerDivisionByZeroException

Finally In Dart Try Catch

The finally block is always executed whether the exceptions occur or not. It is optional to include the final block, but if it is included, it should be after the try and catch block is over.

On block is used when you know what types of exceptions are produced by the program.

Syntax

try {
.....
}
on Exception1 {
....
}
catch Exception2 {
....
}
finally {
// code that should always execute whether an exception or not.
}

Example

void main() {
  int a = 12;
  int b = 0;
  int res;
  try {
    res = a ~/ b;
  } on UnsupportedError {
    print('Cannot divide by zero');
  } catch (ex) {
    print(ex);
  } finally {
    print('Finally block always executed');
  }
}
Show Output
Cannot divide by zero
Finally block always executed

Throwing An Exception

The throw keyword is used to raise an exception explicitly. A raised exception should be handled to prevent the program from exiting unexpectedly.

Syntax

throw new Exception_name() 

Example

void main() {
  try {
    check_account(-10);
  } catch (e) {
    print('The account cannot be negative');
  }
}

void check_account(int amount) {
  if (amount < 0) {
    throw new FormatException(); // Raising explanation externally
  }
}
Show Output
The account cannot be negative

Why Is Exception Handling Needed?

Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. Therefore, exceptions must be handled to prevent the application from unexpected termination. Here are some reasons why exception handling is necessary:

  • To avoid abnormal termination of the program.
  • To avoid an exception caused by logical error.
  • To avoid the program from falling apart when an exception occurs.
  • To reduce the vulnerability of the program.
  • To maintain a good user experience.
  • To try providing aid and some debugging in case of an exception.

How To Create Custom Exception In Dart

As you go advance, you need to create your exception; Dart enables you to create your exception.

Syntax

class YourExceptionClass implements Exception{
  // constructors, variables & methods
}

Example 1: How to Create & Handle Exception

This program throws an exception when a student’s mark is negative. You will understand implements in the object-oriented programming section.

class MarkException implements Exception {
  String errorMessage() {
    return 'Marks cannot be negative value.';
  }
}

void main() {
  try {
    checkMarks(-20);
  } catch (ex) {
    print(ex.toString());
  }
}

void checkMarks(int marks) {
  if (marks < 0) throw MarkException().errorMessage();
}
Show Output
Marks cannot be negative value.

Example 2: How to Create & Handle Exception

This program throws an exception when you find the square root of a negative number.

import 'dart:math';

// custom exception class
class NegativeSquareRootException implements Exception {
  @override
  String toString() {
    return 'Sqauare root of negative number is not allowed here.';
  }
}

// get square root of a positive number
num squareRoot(int i) {
  if (i < 0) {
    // throw `NegativeSquareRootException` exception
    throw NegativeSquareRootException();
  } else {
    return sqrt(i);
  }
}

void main() {
  try {
    var result = squareRoot(-4);

    print("result: $result");
  } on NegativeSquareRootException catch (e) {
    print("Oops, Negative Number: $e");
  } catch (e) {
    print(e);
  } finally {
    print('Job Completed!');
  }
}
Show Output
Oops, Negative Number: Sqauare root of negative number is not allowed here.
Job Completed!


Question For Practice 2

Question For Practice 2

  1. Write a dart program to check if the number is odd or even.
  2. Write a dart program to check whether a character is a vowel or consonant.
  3. Write a dart program to check whether a number is positive, negative, or zero.
  4. Write a dart program to print your name 100 times.
  5. Write a dart program to calculate the sum of natural numbers.
  6. Write a dart program to generate multiplication tables of 5.
  7. Write a dart program to generate multiplication tables of 1-9.
  8. Write a dart program to create a simple calculator that performs addition, subtraction, multiplication, and division.
  9. Write a dart program to print 1 to 100 but not 41.

         



Comments

All Post

When to Use Waterfall vs. Agile

  We compare the benefits and drawbacks of using two well-known software development methodologies, Waterfall and Agile, and lay out when it might be more suitable to use one over the other – or combine practices of both – for your product initiative. When developing a new software product, your team will need to navigate which development methodology is right for your initiative. In the world of managing  software development  projects, the topic of Agile vs Waterfall is widely debated. Many thought leaders and Agile enthusiasts in the industry have argued Waterfall is dead, however, traditional organizational environments and processes have led to it still being widely used today. A 2017 report from the Project Management Institute shows that  51% of the organizations surveyed use Waterfall either often or always . The reality is, each software development project poses its own unique challenges and requirements. It’s not a matter of deciding which development meth...

Flutter form validation: Full guide for you to make Flutter form

  Flutter form validation Getting started with form validation in Flutter The Flutter SDK provides us with an out-of-the-box widget and functionalities to make our lives easier when using form validation. In this article, we’ll cover two approaches to form validation: the form widget and the Provider package. You can find more information on these two approaches in the official Flutter docs. Creating a form in Flutter First, we are going to create a simple login page that has the following fields: Email Name Phone number Password For the validation, we want the users of our app to fill in the correct details in each of these fields. The logic will be defined as such: First, for the name field, we want the user to enter a valid first name and last name, which can be accompanied by initials. For the email field, we want a valid email that contains some characters before the “@” sign, as well as the email domain at the end of the email. For phone number validation, the user is expecte...

How to change the language on Android at runtime and don’t go mad

  How to change the language on Android at runtime and don’t go mad TL;DR There is a library called Lingver that implements the presented approach with just a few lined of code.  Check it out! Introduction The topic is old as the hills, but still is being actively discussed among developers due to frequent API and behavior changes. The goal of this post is to gather all tips and address all pitfalls while implementing this functionality. Disclaimer Changing the language on Android at runtime was never officially encouraged or documented. The resource framework automatically selects the resources that best match the device. Such behavior is enough for common applications, so just make sure you have strict reasons to change it before proceeding further. There are a ton of articles and answers on Stack Overflow but they usually lack enough of explanation. As a result, when this functionality gets broken, developers can’t easily fix it due to the messy API and lots of deprecated t...

7 Key Android Concepts

  Although the Android platform is open and customizable, Android users have become accustomed to constructs developed by Google for Android devices. Although the Android platform is open and customizable, Android users have become accustomed to constructs developed by Google for Android devices. Moreover, the use of these Android concepts is vital in developing an application quickly – custom Android designs can take up to 10 times longer! Android UI Controls Android provides a number of standard UI controls that  enable a rich user experience . Designers and developers should thoroughly understand all of these controls for the following reasons: They are faster to implement. It can take up to ten times longer to develop a custom control than to implement a user interface with standard Android controls. They ensure good performance. Custom controls rarely function as expected in their first implementation. By implementing standard controls, you can eliminate the need to test,...

Clean Code and the Art of Exception Handling

  Clean Code and the Art of Exception Handling Exceptions are as old as programming itself. An unhandled exception may cause unexpected behavior, and results can be spectacular. Over time, these errors have contributed to the impression that exceptions are bad. But exceptions are a fundamental element of modern programming. Rather than fearing exceptions, we should embrace them and learn how to benefit from them. In this article, we will discuss how to manage exceptions elegantly, and use them to write clean code that is more maintainable. Exceptions are as old as programming itself. Back in the days when programming was done in hardware, or via low-level programming languages, exceptions were used to alter the flow of the program, and to avoid hardware failures. Today, Wikipedia  defines exceptions as: anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution specialized programming language constructs or computer h...

How to them the background of the Android options menu items

  “What we’ve got here is… failure to theme. Some views you just can’t reach. So you get what we had here last project, which is the way Android wants it… well, it gets it. I don’t like it any more than you men.” – Captain, Road Prison 36 Some of you might recognize the previous paragraph as the introduction of Guns ‘N Roses’ Civil War or from the movie Cold Hand Luke starring Paul Newman. This is the feeling I get when I try to create a custom theme for an application on Android. The Android SDK does permit some level of theming, which is not really well documented to start with. Other things are hard-coded, “so you get what we had here last project”. Now, one of the things your application will most likely use is the Options menu, which is the menu you see when you press the hard menu key. It is kind of… orange. In our last project, we had to completely remove the orange in favor of our customer’s color scheme, which is on the blue side. I couldn’t find a way to change the menu i...

Android Jetpack Compose

  Jetpack Compose Tutorial for Android: Getting Started Jetpack Compose is Android’s modern toolkit for building native UI. It simplifies and accelerates UI development on Android. Quickly bring your app to life with less code, powerful tools, and intuitive Kotlin APIs. At Google I/O 2019, Google first announced  Jetpack Compose . Jetpack Compose is Google’s response to the declarative UI framework trend, which the Android team is developing to fundamentally change the way developers create UI, making it easier and faster to write, and more performant to run. It is a part of the Jetpack suite of libraries and as such should provide compatibility throughout platform versions, removing the need to avoid certain features, because you’re targeting lower-end devices or older versions of Android. Although it’s still in an alpha , Compose is already making big waves in the Android community. If you want to stay up-to-date on the latest and greatest technology, read on! In this tutor...

MVVM architecture, ViewModel and LiveData (Part 1)

  MVVM architecture, ViewModel and LiveData (Part 1) During Google I/O, Google introduced  architecture components  which includes  LiveData  and  ViewModel  which facilitates developing Android app using MVVM pattern. This article discusses how can these components serve an android app that follows MVVM. Quick Definition of MVVM If you are familiar with MVVM, you can skip this section completely. MVVM is one of the architectural patterns which enhances separation of concerns, it allows separating the user interface logic from the business (or the back-end) logic. Its target (with other MVC patterns goal) is to achieve the following principle  “Keeping UI code simple and free of app logic in order to make it easier to manage” . MVVM has mainly the following layers: Model Model represents the data and business logic of the app. One of the recommended implementation strategies of this layer, is to expose its data through observables to be decoupled ...