DEV Community

Bill Odida
Bill Odida

Posted on

Data Structures And Algorithms in Dart : Arrays

In Dart, an array is an ordered list of items. You can use an array to store a collection of items, such as a list of names or a list of numbers.

To create an array in Dart, you can use the List type and specify the type of elements that the array will hold within angle brackets (< and >). For example:

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

Enter fullscreen mode Exit fullscreen mode

This creates an array of integers called numbers with the elements 1, 2, 3, 4, and 5.

You can also use the new keyword to create an array:

List<String> names = new List<String>();

Enter fullscreen mode Exit fullscreen mode

Arrays have many useful methods for adding, removing, and manipulating elements.

Some of the most common methods include :

Here are some common methods that you can use with arrays in Dart:

We will be using the following lists to explain the core array methods in Dart :


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

List<dynamic> mixed = [1, '2', 3.0, true, [4, 5]];

Enter fullscreen mode Exit fullscreen mode
  • add(element): Adds an element to the end of the array.
// Add an element to the end of the array
numbers.add(6); // [1, 2, 3, 4, 5, 6]

Enter fullscreen mode Exit fullscreen mode
  • addAll(elements): Adds all the elements of an iterable to the end of the array.

// Add multiple elements to the end of the array
numbers.addAll([7, 8, 9]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Enter fullscreen mode Exit fullscreen mode
  • clear(): Removes all elements from the array.
numbers.clear();
Enter fullscreen mode Exit fullscreen mode
  • remove(element): Removes the first occurrence of an element from the array.
// Remove the first occurrence of an element from the array
numbers.remove(3); // [1, 2, 4, 5, 6, 7, 8, 9]

Enter fullscreen mode Exit fullscreen mode
  • removeAt(index): Removes the element at a specific index from the array.
// Remove the element at a specific index from the array
numbers.removeAt(2); // [1, 2, 5, 6, 7, 8, 9]

Enter fullscreen mode Exit fullscreen mode
  • removeLast(): Removes the last element from the array.
// Remove the last element from the array
numbers.removeLast(); // [1, 2, 5, 6, 7, 8]

Enter fullscreen mode Exit fullscreen mode
  • removeRange(start, end): Removes a range of elements from the array.
// Remove a range of elements from the array
numbers.removeRange(1, 3); // [1, 8]

Enter fullscreen mode Exit fullscreen mode
  • insert(index, element): Inserts an element at a specific index in the array.
// Insert an element at a specific index in the array
numbers.insert(1, 2); // [1, 2, 8]

Enter fullscreen mode Exit fullscreen mode
  • insertAll(index, elements): Inserts all the elements of an iterable at a specific index in the array.
// Insert multiple elements at a specific index in the array
numbers.insertAll(1, [3, 4, 5]); // [1, 3, 4, 5, 2, 8]

Enter fullscreen mode Exit fullscreen mode
  • sort([compare]): Sorts the elements in the array according to the provided comparator function.
// Sort the elements in the array
numbers.sort(); // [1, 2, 3, 4, 5, 8]

Enter fullscreen mode Exit fullscreen mode
  • indexOf(element): Returns the index of the first occurrence of an element in the array, or -1 if the element is not found.
// Get the index of the first occurrence of an element in the array
int index = numbers.indexOf(4); // 3

Enter fullscreen mode Exit fullscreen mode
  • lastIndexOf(element): Returns the index of the last occurrence of an element in the array, or -1 if the element is not found.
// Get the index of the last occurrence of an element in the array
int lastIndex = numbers.lastIndexOf(4); // 3

Enter fullscreen mode Exit fullscreen mode
  • sublist(start, [end]): Returns a new list containing the elements in a range of the array.
// Get a new list containing the elements in a range of the array
List<int> sublist = numbers.sublist(1, 3); // [2, 3]

Enter fullscreen mode Exit fullscreen mode
  • asMap(): Returns a new map view of the array.
// Get a new map view of the array
Map<int, int> map = numbers.asMap(); // {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 8}

Enter fullscreen mode Exit fullscreen mode
  • forEach(function): Calls the provided function on each element in the array.
// Call a function on each element in the array
numbers.forEach((element) {
  print(element);
});
Enter fullscreen mode Exit fullscreen mode
  • fold(initialValue, combine): Reduces the array to a single value by repeatedly calling the combine function on the elements of the array, starting with the initialValue.
// Use .fold() to add all the elements in the array
int sum = numbers.fold(0, (prev, element) => prev + element); // 15

Enter fullscreen mode Exit fullscreen mode
  • generate(generator, [count]): Creates a new array where the elements are generated by calling the generator function. If the count parameter is provided, it specifies the number of elements to generate.
// Use .generate() to create an array of 10 random numbers
Random random = new Random();
List<int> randomNumbers = List.generate(10, (_) => random.nextInt(100));

Enter fullscreen mode Exit fullscreen mode
  • any(test): Returns true if at least one element of the array satisfies the provided test function.
// Check if any element in the array is greater than 4
bool anyGreaterThanFour = numbers.any((element) => element > 4); // true

Enter fullscreen mode Exit fullscreen mode
  • contains(element): Returns true if the array contains the specified element.
/ Check if the array contains the number 3
bool containsThree = numbers.contains(3); // true

Enter fullscreen mode Exit fullscreen mode
  • elementAt(index): Returns the element at the specified index in the array.
// Get the element at index 2 in the array
int elementAtIndexTwo = numbers.elementAt(2); // 3

Enter fullscreen mode Exit fullscreen mode
  • every(test): Returns true if every element of the array satisfies the provided test function.
// Check if every element in the array is greater than 0
bool allGreaterThanZero = numbers.every((element) => element > 0); // true

Enter fullscreen mode Exit fullscreen mode
  • expand(function): Returns a new array where each element is replaced by the elements returned by the function.

// Expand the array by multiplying each element by 2
List<int> expanded = numbers.expand((element) => [element * 2]).toList(); // [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode
  • fillRange(start, end, fillValue): Sets the elements in a range of the array to a specified value.
// Set the elements in the second half of the array to 0
numbers.fillRange(2, 5, 0); // [1, 2, 0, 0, 0]

Enter fullscreen mode Exit fullscreen mode
  • firstWhere(test, [orElse]): Returns the first element that satisfies the provided test function, or a default value if no such element is found.
// Get the first element that is greater than 2
int firstGreaterThanTwo = numbers.firstWhere((element) => element > 2, orElse: () => null); // 0

Enter fullscreen mode Exit fullscreen mode
  • cast(): Casts the elements in the array to a specified type.
// Cast the elements of the array to type int
List<int> castToInt = mixed.cast<int>().toList(); // [1, 3]

Enter fullscreen mode Exit fullscreen mode
  • followedBy(other): Returns a new array containing the elements of the current array followed by the elements of another iterable.

  • join([separator]): Concatenates the elements in the array into a single string, with an optional separator string between each element.

// Concatenate the elements of the array into a single string
String joined = mixed.join(', '); // '1, 2, 3.0, true, [4, 5]'

Enter fullscreen mode Exit fullscreen mode
  • lastWhere(test, [orElse]): Returns the last element that satisfies the provided test function, or a default value if no such element is found.
// Get the last element that is a boolean
bool lastBool = mixed.lastWhere((element) => element is bool, orElse: () => null); // true

Enter fullscreen mode Exit fullscreen mode
  • map(function): Returns a new array where each element is the result of calling the function on the corresponding element of the original array.
// Multiply each element in the array by 2
List<int> multiplied = mixed.map((element) => element * 2).toList(); // [2, '22', 6.0, true, [4, 5]]

Enter fullscreen mode Exit fullscreen mode
  • reduce(combine): Reduces the array to a single value by repeatedly calling the combine function on the elements of the array.
// Reduce the array to a single value by adding the elements
int sum = mixed.reduce((prev, element) => prev + element); // 15.0

Enter fullscreen mode Exit fullscreen mode
  • singleWhere(test, [orElse]): Returns the only element that satisfies the provided test function, or a default value if no such element is found.
// Get the only element that is a string
String singleString = mixed.singleWhere((element) => element is String, orElse: () => null); // '2

Enter fullscreen mode Exit fullscreen mode
  • skip(count): Returns a new array that skips the first count elements of the original array.
// Skip the first two elements of the array
List<dynamic> skipped = mixed.skip(2).toList(); // [3.0, true, [4, 5]]

Enter fullscreen mode Exit fullscreen mode
  • skipWhile(test): Returns a new array that skips elements from the original array while they satisfy the provided test function.
// Skip elements of the array while they are not a boolean
List<dynamic> skippedWhile = mixed.skipWhile((element) => element is! bool).toList(); // [true, [4, 5]]

Enter fullscreen mode Exit fullscreen mode
  • take(count): Returns a new array that contains the first count elements of the original array.
// Take the first three elements of the array
List<dynamic> taken = mixed.take(3).toList(); // [1, '2', 3.0]

Enter fullscreen mode Exit fullscreen mode
  • takeWhile(test): Returns a new array that contains elements from the original array while they satisfy the provided test function.
// Take elements of the array while they are not a boolean
List<dynamic> takenWhile = mixed.takeWhile((element) => element is! bool).toList(); // [1, '2', 3.0]
Enter fullscreen mode Exit fullscreen mode
  • toList(): Returns a new list with the elements of the original array.
// Convert the array to a list
List<dynamic> toList = mixed.toList(); // [1, '2', 3.0, true, [4, 5]]
Enter fullscreen mode Exit fullscreen mode
  • toSet(): Returns a new set with the elements of the original array.
// Convert the array to a set
Set<dynamic> toSet = mixed.toSet(); // {1, '2', 3.0, true, [4, 5]}

Enter fullscreen mode Exit fullscreen mode
  • toString(): Returns a string representation of the array. where(test): Returns a new array containing only the elements of the original array that satisfy the provided test function.
// Convert the array to a string
String toString = mixed.toString(); // '[1, 2, 3.0, true, [4, 5]]'

Enter fullscreen mode Exit fullscreen mode
  • whereType(): Returns a new array containing only the elements of the original array that are of the specified type.

// Get only the elements of the array that are a boolean
List<dynamic> whereBool = mixed.where((element) => element is bool).toList(); // [true]

// Get only the elements of the array that are a double
List<dynamic> whereDouble = mixed.whereType<double>().toList(); // [3.0]

Enter fullscreen mode Exit fullscreen mode

Top comments (0)