OneBite.Dev - Coding blog in a bite size

Check If Array Is Empty In Dart

Code snippet for how to Check If Array Is Empty In Dart with sample and detail explanation

Dart is a popular programming language that offers various functionalities. One of the commonly encountered situations while coding in Dart is to check whether an array, also known as a list in Dart, is empty or not. This article will guide you on how you can easily achieve that.

Check If Array Is Empty In Dart: Code Snippet

Here is a sample Dart code that checks whether a list or array is empty or not:

void main() {
  List<int> numList = [];
  if (numList.isEmpty) {
    print('Array is empty!');
  } else {
    print('Array is not empty!');
  }
}

Code Explanation: Check If Array Is Empty In Dart

The aforementioned code can be thoroughly explained in the following steps:

Step 1: We first declare a list named numList and initialize it as empty. In Dart, we use List for array declaration.

List<int> numList = [];

Step 2: Now, to check if this list is empty, we use the isEmpty property of the List class. This property returns true if the list is empty and false if it is not.

if (numList.isEmpty) {
}

Step 3: Inside the if condition, if numList.isEmpty returns true, we print “Array is empty!“. In Dart, print statements are used to output text on the console.

print('Array is empty!');

Step 4: If the isEmpty property returns false, it means our list or array is not empty. In such cases, the else block will be executed and we print out “Array is not empty!“.

else {
  print('Array is not empty!');
}

Through this simple code snippet, you can easily check the emptiness of an array in Dart. Ensure to replace numList with the array you want to check. Try running the code with different array values to better understand how it works.

dart