OneBite.Dev - Coding blog in a bite size

Count Array's Length In Dart

Code snippet for how to Count Array's Length In Dart with sample and detail explanation

Understanding array lengths is a fundamental aspect of Dart programming. This guide provides quick and easy insights into how to count an array’s length in Dart.

Code snippet for Counting Array’s Length in Dart

To start, let’s look at a straightforward code snippet:

void main() {
  List array = [1, 2, 3, 4, 5];
  print('Array Length: ${array.length}');
}

This simple program demonstrates how to find out the size or length of an array in Dart.

Code Explanation for Counting Array’s Length in Dart

Now, let’s break down the above code step by step to understand how it works.

  1. Defining the array: In the first line within the main function, we define an array with the name “array”.
List array = [1, 2, 3, 4, 5];

This array contains 5 elements - 1, 2, 3, 4 and 5.

  1. Printing the array’s length: The next line is where we print the length or size of the array.
print('Array Length: ${array.length}');

In Dart, we use the length property to get the number of items in an array (in this case, “array”). We insert this property into a String with the ”${…}” syntax, which enables us to evaluate Dart expressions inside the String. So, ”${array.length}” evaluates to the length of the array.

Upon running the code, it prints:

Array Length: 5

indicating the array’s length.

And that’s it! You can count the number of items in any array by using this simple ‘.length’ property. You just need to replace “array” with the name of your array. This method is very straightforward and doesn’t require looping through the array, making it a more efficient option.

dart