OneBite.Dev - Coding blog in a bite size

Find The Length Of An Array In Dart

Code snippet for how to Find The Length Of An Array In Dart with sample and detail explanation

Understanding how to determine the length of an array in Dart is a crucial part of the Dart programming language. This article will provide a simple code snippet and an easy-to-understand explanation.

Code snippet: Find The Length Of An Array In Dart

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

Code Explanation for Find The Length Of An Array In Dart

Let’s break down the code step by step for a better understanding.

First, we need to understand what the main function is in Dart:

void main() { 

In dart, every app must have a top-level main() function, which serves as the entry point to the app. The main() function returns void and has an optional List parameter for arguments.

Next, we define the Array:

List<int> intArray = [1, 2, 3, 4, 5]; 

In Dart, arrays are List objects. Here, we created a list of integers named ‘intArray’ and assigned it five elements: 1, 2, 3, 4, and 5.

Finally, we use the ‘print’ and ‘length’ functions to find the length of our array:

print('Length of Array : ${intArray.length}'); 

Here, the ${intArray.length} gets the number of items in the intArray list. ‘print’ then outputs this length to the console.

In this case, running this code snippet would output:

Length of Array : 5

This output displays that our ‘intArray’ has five elements. Thus, understanding how to determine the length of an array, or a List in Dart, is simple and straightforward!

dart