How to Get the Length of a List in Dart or Flutter?

To get the length of a List in Dart, you can use the length property of the List object. The length property is a read-only property that returns the total number of items in a List as an integer value.

The following example shows how you can get the length of a list using the length property:

void main(){

  // Create the list
  var numbers = [1, 2, 3, 4, 5];
  
  // Get List's length
  int listLength = numbers.length;
  
  // Print the result
  print('The length of the list is $listLength');
  
}

Output:

The length of the list is 5

If there are no items in the list, then the length property returns 0. The zero(0) value of the length property indicates that the list is empty.

See the following example:

void main(){

  // Create the list
  var emptyList = [ ];
  
  // Get List's length
  int listLength = emptyList.length;
  
  // Print the result
  print('The length of the list is $listLength');
  
}

Output:

The length of the list is 0

Get the Length of the List using a for…in Loop

You can also use a for..in loop to get the length of the list.

In Dart, a for...in loop is used to iterate over the elements of an iterable, such as a list or a map.

The basic syntax of a for...in loop is as follows:

for (variable in iterable) {
  // code to execute for each element
}

Here variable is the variable that will take on the value of each element of the iterable in each iteration of the loop, and iterable is an object that implements the Iterable interface, such as a List or a Set.

Now, if you want to get the length of a List using a for…in loop, you can initialize a count variable with 0 and increment it by 1 in each iteration of the loop. Once the loop completes, the count variable will hold a value same as the size of the list.

See the implementation in the following example:

void main(){

  // Create the list
  var numbers = [1, 2, 3, 4, 5];
  
  // Initialize the count 
  int count = 0;
  
  // Loop through the list
  for( int num in numbers ){
    
    // Increment count by one on each iteration
    count = count + 1;
    
  }
  
  // Print the result
  print('The length of the list is $count');
  
}

Output:

The length of the list is 5

Conclusion

In this article, we learned how we can get the length of a list in Dart.

In summary, you can use the length property of the List object to get the length of the specified list. You can also run a for...in loop over the list and count the total items in it to get the total size.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.